diff --git a/.ionide/symbolCache.db b/.ionide/symbolCache.db new file mode 100644 index 0000000..8a73c4f Binary files /dev/null and b/.ionide/symbolCache.db differ diff --git a/.vs/Znyc.Dispatching/DesignTimeBuild/.dtbcache.v2 b/.vs/Znyc.Dispatching/DesignTimeBuild/.dtbcache.v2 new file mode 100644 index 0000000..f92d16d Binary files /dev/null and b/.vs/Znyc.Dispatching/DesignTimeBuild/.dtbcache.v2 differ diff --git a/.vs/Znyc.Dispatching/config/applicationhost.config b/.vs/Znyc.Dispatching/config/applicationhost.config new file mode 100644 index 0000000..b96f9bc --- /dev/null +++ b/.vs/Znyc.Dispatching/config/applicationhost.config @@ -0,0 +1,998 @@ + + + + + + +
+
+
+
+
+
+
+
+ + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+
+
+
+
+
+ +
+
+
+
+
+ +
+
+
+ +
+
+ +
+
+ +
+
+
+ + +
+
+
+
+
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.vs/Znyc.Dispatching/v16/.suo b/.vs/Znyc.Dispatching/v16/.suo new file mode 100644 index 0000000..c4114ba Binary files /dev/null and b/.vs/Znyc.Dispatching/v16/.suo differ diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..8524d96 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,69 @@ +{ + // 使用 IntelliSense 了解相关属性。 + // 悬停以查看现有属性的描述。 + // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/bin/Debug//", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + "console": "internalConsole", + "pipeTransport": { + "pipeCwd": "${workspaceFolder}", + "pipeProgram": "enter the fully qualified path for the pipe program name, for example '/usr/bin/ssh'", + "pipeArgs": [], + "debuggerPath": "enter the path for the debugger on the target machine, for example ~/vsdbg/vsdbg" + } + }, + { + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/bin/Debug//", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/bin/Debug//", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + "console": "internalConsole" + }, + + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/bin/Debug//", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + "console": "internalConsole" + } + + ] +} \ No newline at end of file diff --git a/.vscode/solution-explorer/class.cs-template b/.vscode/solution-explorer/class.cs-template new file mode 100644 index 0000000..015da46 --- /dev/null +++ b/.vscode/solution-explorer/class.cs-template @@ -0,0 +1,8 @@ +using System; + +namespace {{namespace}} +{ + public class {{name}} + { + } +} diff --git a/.vscode/solution-explorer/class.ts-template b/.vscode/solution-explorer/class.ts-template new file mode 100644 index 0000000..ff2edef --- /dev/null +++ b/.vscode/solution-explorer/class.ts-template @@ -0,0 +1,3 @@ +export class {{name}} { + +} \ No newline at end of file diff --git a/.vscode/solution-explorer/class.vb-template b/.vscode/solution-explorer/class.vb-template new file mode 100644 index 0000000..38ef67f --- /dev/null +++ b/.vscode/solution-explorer/class.vb-template @@ -0,0 +1,9 @@ +Imports System + +Namespace {{namespace}} + + Public Class {{name}} + + End Class + +End Namespace diff --git a/.vscode/solution-explorer/default.ts-template b/.vscode/solution-explorer/default.ts-template new file mode 100644 index 0000000..04af870 --- /dev/null +++ b/.vscode/solution-explorer/default.ts-template @@ -0,0 +1,3 @@ +export default {{name}} { + +} \ No newline at end of file diff --git a/.vscode/solution-explorer/enum.cs-template b/.vscode/solution-explorer/enum.cs-template new file mode 100644 index 0000000..7d4cdee --- /dev/null +++ b/.vscode/solution-explorer/enum.cs-template @@ -0,0 +1,8 @@ +using System; + +namespace {{namespace}} +{ + public enum {{name}} + { + } +} diff --git a/.vscode/solution-explorer/interface.cs-template b/.vscode/solution-explorer/interface.cs-template new file mode 100644 index 0000000..6b5dec1 --- /dev/null +++ b/.vscode/solution-explorer/interface.cs-template @@ -0,0 +1,8 @@ +using System; + +namespace {{namespace}} +{ + public interface {{name}} + { + } +} diff --git a/.vscode/solution-explorer/interface.ts-template b/.vscode/solution-explorer/interface.ts-template new file mode 100644 index 0000000..3ea404b --- /dev/null +++ b/.vscode/solution-explorer/interface.ts-template @@ -0,0 +1,3 @@ +export interface {{name}} { + +} \ No newline at end of file diff --git a/.vscode/solution-explorer/template-list.json b/.vscode/solution-explorer/template-list.json new file mode 100644 index 0000000..2849622 --- /dev/null +++ b/.vscode/solution-explorer/template-list.json @@ -0,0 +1,46 @@ +{ + "templates": [ + { + "name": "Class", + "extension": "cs", + "file": "./class.cs-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Interface", + "extension": "cs", + "file": "./interface.cs-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Enum", + "extension": "cs", + "file": "./enum.cs-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Class", + "extension": "ts", + "file": "./class.ts-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Interface", + "extension": "ts", + "file": "./interface.ts-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Default", + "extension": "ts", + "file": "./default.ts-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Class", + "extension": "vb", + "file": "./class.vb-template", + "parameters": "./template-parameters.js" + } + ] +} \ No newline at end of file diff --git a/.vscode/solution-explorer/template-parameters.js b/.vscode/solution-explorer/template-parameters.js new file mode 100644 index 0000000..daba8b2 --- /dev/null +++ b/.vscode/solution-explorer/template-parameters.js @@ -0,0 +1,17 @@ +var path = require("path"); + +module.exports = function(filename, projectPath, folderPath) { + var namespace = "Unknown"; + if (projectPath) { + namespace = path.basename(projectPath, path.extname(projectPath)); + if (folderPath) { + namespace += "." + folderPath.replace(path.dirname(projectPath), "").substring(1).replace(/[\\\/]/g, "."); + } + namespace = namespace.replace(/[\\\-]/g, "_"); + } + + return { + namespace: namespace, + name: path.basename(filename, path.extname(filename)) + } +}; \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..31c32bd --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,24 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "shell", + "args": [ + "build", + // Ask dotnet build to generate full paths for file names. + "/property:GenerateFullPaths=true", + // Do not generate summary otherwise it leads to duplicate errors in Problems panel + "/consoleloggerparameters:NoSummary" + ], + "group": "build", + "presentation": { + "reveal": "silent" + }, + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..0012440 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,34 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + + + +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +WORKDIR /src +COPY ["Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj", "Znyc.Dispatching.Web.Entry/"] +COPY ["Znyc.Dispatching.Web.Core/Znyc.Dispatching.Web.Core.csproj", "Znyc.Dispatching.Web.Core/"] +COPY ["Znyc.Dispatching.Database.Migrations/Znyc.Dispatching.Database.Migrations.csproj", "Znyc.Dispatching.Database.Migrations/"] +COPY ["Znyc.Dispatching.EntityFramework.Core/Znyc.Dispatching.EntityFramework.Core.csproj", "Znyc.Dispatching.EntityFramework.Core/"] +COPY ["Znyc.Dispatching.Core/Znyc.Dispatching.Core.csproj", "Znyc.Dispatching.Core/"] +COPY ["Znyc.Dispatching.Application/Znyc.Dispatching.Application.csproj", "Znyc.Dispatching.Application/"] +COPY ["Znyc.Dispatching.MongoDb.Repository/Znyc.Dispatching.MongoDb.Repository.csproj", "Znyc.Dispatching.MongoDb.Repository/"] +COPY ["Znyc.Dispatching.WeChat.Core/Znyc.Dispatching.WeChat.Core.csproj", "Znyc.Dispatching.WeChat.Core/"] +RUN dotnet restore "Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj" +COPY . . +WORKDIR "/src/Znyc.Dispatching.Web.Entry" +RUN dotnet build "Znyc.Dispatching.Web.Entry.csproj" -c Release -o /app/build + +FROM build AS publish +RUN dotnet publish "Znyc.Dispatching.Web.Entry.csproj" -c Release -o /app/publish + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Znyc.Dispatching.Web.Entry.dll"] \ No newline at end of file diff --git a/src/.dockerignore b/src/.dockerignore new file mode 100644 index 0000000..3729ff0 --- /dev/null +++ b/src/.dockerignore @@ -0,0 +1,25 @@ +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md \ No newline at end of file diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..be42968 --- /dev/null +++ b/src/.gitignore @@ -0,0 +1,28 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates +*.log + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the \ No newline at end of file diff --git a/src/.vscode/launch.json b/src/.vscode/launch.json new file mode 100644 index 0000000..69f0818 --- /dev/null +++ b/src/.vscode/launch.json @@ -0,0 +1,34 @@ +{ + // 使用 IntelliSense 了解相关属性。 + // 悬停以查看现有属性的描述。 + // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/Znyc.Dispatching.Web.Entry/bin/Debug/net5.0/Znyc.Dispatching.Web.Entry.dll", + "args": [], + "cwd": "${workspaceFolder}/Znyc.Dispatching.Web.Entry", + "stopAtEntry": false, + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} \ No newline at end of file diff --git a/src/.vscode/solution-explorer/class.cs-template b/src/.vscode/solution-explorer/class.cs-template new file mode 100644 index 0000000..015da46 --- /dev/null +++ b/src/.vscode/solution-explorer/class.cs-template @@ -0,0 +1,8 @@ +using System; + +namespace {{namespace}} +{ + public class {{name}} + { + } +} diff --git a/src/.vscode/solution-explorer/class.ts-template b/src/.vscode/solution-explorer/class.ts-template new file mode 100644 index 0000000..ff2edef --- /dev/null +++ b/src/.vscode/solution-explorer/class.ts-template @@ -0,0 +1,3 @@ +export class {{name}} { + +} \ No newline at end of file diff --git a/src/.vscode/solution-explorer/class.vb-template b/src/.vscode/solution-explorer/class.vb-template new file mode 100644 index 0000000..38ef67f --- /dev/null +++ b/src/.vscode/solution-explorer/class.vb-template @@ -0,0 +1,9 @@ +Imports System + +Namespace {{namespace}} + + Public Class {{name}} + + End Class + +End Namespace diff --git a/src/.vscode/solution-explorer/default.ts-template b/src/.vscode/solution-explorer/default.ts-template new file mode 100644 index 0000000..04af870 --- /dev/null +++ b/src/.vscode/solution-explorer/default.ts-template @@ -0,0 +1,3 @@ +export default {{name}} { + +} \ No newline at end of file diff --git a/src/.vscode/solution-explorer/enum.cs-template b/src/.vscode/solution-explorer/enum.cs-template new file mode 100644 index 0000000..7d4cdee --- /dev/null +++ b/src/.vscode/solution-explorer/enum.cs-template @@ -0,0 +1,8 @@ +using System; + +namespace {{namespace}} +{ + public enum {{name}} + { + } +} diff --git a/src/.vscode/solution-explorer/interface.cs-template b/src/.vscode/solution-explorer/interface.cs-template new file mode 100644 index 0000000..6b5dec1 --- /dev/null +++ b/src/.vscode/solution-explorer/interface.cs-template @@ -0,0 +1,8 @@ +using System; + +namespace {{namespace}} +{ + public interface {{name}} + { + } +} diff --git a/src/.vscode/solution-explorer/interface.ts-template b/src/.vscode/solution-explorer/interface.ts-template new file mode 100644 index 0000000..3ea404b --- /dev/null +++ b/src/.vscode/solution-explorer/interface.ts-template @@ -0,0 +1,3 @@ +export interface {{name}} { + +} \ No newline at end of file diff --git a/src/.vscode/solution-explorer/template-list.json b/src/.vscode/solution-explorer/template-list.json new file mode 100644 index 0000000..2849622 --- /dev/null +++ b/src/.vscode/solution-explorer/template-list.json @@ -0,0 +1,46 @@ +{ + "templates": [ + { + "name": "Class", + "extension": "cs", + "file": "./class.cs-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Interface", + "extension": "cs", + "file": "./interface.cs-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Enum", + "extension": "cs", + "file": "./enum.cs-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Class", + "extension": "ts", + "file": "./class.ts-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Interface", + "extension": "ts", + "file": "./interface.ts-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Default", + "extension": "ts", + "file": "./default.ts-template", + "parameters": "./template-parameters.js" + }, + { + "name": "Class", + "extension": "vb", + "file": "./class.vb-template", + "parameters": "./template-parameters.js" + } + ] +} \ No newline at end of file diff --git a/src/.vscode/solution-explorer/template-parameters.js b/src/.vscode/solution-explorer/template-parameters.js new file mode 100644 index 0000000..daba8b2 --- /dev/null +++ b/src/.vscode/solution-explorer/template-parameters.js @@ -0,0 +1,17 @@ +var path = require("path"); + +module.exports = function(filename, projectPath, folderPath) { + var namespace = "Unknown"; + if (projectPath) { + namespace = path.basename(projectPath, path.extname(projectPath)); + if (folderPath) { + namespace += "." + folderPath.replace(path.dirname(projectPath), "").substring(1).replace(/[\\\/]/g, "."); + } + namespace = namespace.replace(/[\\\-]/g, "_"); + } + + return { + namespace: namespace, + name: path.basename(filename, path.extname(filename)) + } +}; \ No newline at end of file diff --git a/src/.vscode/tasks.json b/src/.vscode/tasks.json new file mode 100644 index 0000000..85740d9 --- /dev/null +++ b/src/.vscode/tasks.json @@ -0,0 +1,42 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "${workspaceFolder}/Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/src/Dockerfile b/src/Dockerfile new file mode 100644 index 0000000..c221dd2 --- /dev/null +++ b/src/Dockerfile @@ -0,0 +1,33 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + + +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +WORKDIR /src +COPY ["Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj", "Znyc.Dispatching.Web.Entry/"] +COPY ["Znyc.Dispatching.Web.Core/Znyc.Dispatching.Web.Core.csproj", "Znyc.Dispatching.Web.Core/"] +COPY ["Znyc.Dispatching.Database.Migrations/Znyc.Dispatching.Database.Migrations.csproj", "Znyc.Dispatching.Database.Migrations/"] +COPY ["Znyc.Dispatching.EntityFramework.Core/Znyc.Dispatching.EntityFramework.Core.csproj", "Znyc.Dispatching.EntityFramework.Core/"] +COPY ["Znyc.Dispatching.Core/Znyc.Dispatching.Core.csproj", "Znyc.Dispatching.Core/"] +COPY ["Znyc.Dispatching.Application/Znyc.Dispatching.Application.csproj", "Znyc.Dispatching.Application/"] +COPY ["Znyc.Dispatching.MongoDb.Repository/Znyc.Dispatching.MongoDb.Repository.csproj", "Znyc.Dispatching.MongoDb.Repository/"] +COPY ["Znyc.Dispatching.WeChat.Core/Znyc.Dispatching.WeChat.Core.csproj", "Znyc.Dispatching.WeChat.Core/"] +RUN dotnet restore "Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj" +COPY . . +WORKDIR "/src/Znyc.Dispatching.Web.Entry" +RUN dotnet build "Znyc.Dispatching.Web.Entry.csproj" -c Release -o /app/build + +FROM build AS publish +RUN dotnet publish "Znyc.Dispatching.Web.Entry.csproj" -c Release -o /app/publish + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Znyc.Dispatching.Web.Entry.dll"] \ No newline at end of file diff --git a/src/Znyc.Dispatchimg.Test/ServiceTests/LoginServiceTest.cs b/src/Znyc.Dispatchimg.Test/ServiceTests/LoginServiceTest.cs new file mode 100644 index 0000000..d9aecc3 --- /dev/null +++ b/src/Znyc.Dispatchimg.Test/ServiceTests/LoginServiceTest.cs @@ -0,0 +1,18 @@ +using Furion; +using Znyc.Dispatching.Application; + +namespace Znyc.Dispatching.Tests.ServiceTests +{ + /// + /// 登录单元测试 + /// + public class LoginServiceTest + { + private readonly ILoginService _loginService; + public LoginServiceTest() + { + _loginService = App.GetService(); + } + + } +} diff --git a/src/Znyc.Dispatchimg.Test/ServiceTests/VehicleServiceTest.cs b/src/Znyc.Dispatchimg.Test/ServiceTests/VehicleServiceTest.cs new file mode 100644 index 0000000..a801d57 --- /dev/null +++ b/src/Znyc.Dispatchimg.Test/ServiceTests/VehicleServiceTest.cs @@ -0,0 +1,77 @@ +using Furion; +using Furion.DatabaseAccessor; +using Xunit; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Tests +{ + /// + /// 车辆测试 + /// + public class VehicleServiceTest + { + private readonly IRepository _employeeRepository; + + /// private readonly ilo _vehicleService; + public VehicleServiceTest() + { + _employeeRepository = App.GetService>(); + } + + /// + /// 根据id获取车辆信息 + /// + [Fact] + public async void GetVehicleByIdAsync() + { + Employee res = await _employeeRepository.FindAsync(162538803421253); + Assert.NotNull(res); + } + + ///// + ///// 根据id获取车辆Gps信息 + ///// + //[Fact] + //public async void GetVehicleGpsByIdAsync() + //{ + // var res = await _vehicleService.GetVehicleGpsByIdAsync(162538803421253); + // Assert.NotNull(res); + //} + ///// + ///// 获取地图信息 + ///// + //[Fact] + //public async void GetMapMonitorAsync() + //{ + // var res = await _vehicleService.GetMapMonitorAsync(); + // Assert.NotNull(res); + //} + + ///// + ///// 分页查询 + ///// + //[Fact] + //public async void PageAsync() + //{ + // var res = await _vehicleService.PageAsync(0, 1, 10); + // Assert.NotNull(res); + //} + + ///// + ///// 修改车辆信息 + ///// + //[Fact] + //public async void UpdateAsync() + //{ + // VehicleUpdateInput input = new VehicleUpdateInput() + // { + // VehicleCode = "Z01", + // VehiclePlate = "粤", + // ContactPerson = "单元", + // ContactPhone = "13111111111" + // }; + // await _vehicleService.UpdateAsync(input); + // Assert.True(true); + //} + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatchimg.Test/Startup.cs b/src/Znyc.Dispatchimg.Test/Startup.cs new file mode 100644 index 0000000..29ba202 --- /dev/null +++ b/src/Znyc.Dispatchimg.Test/Startup.cs @@ -0,0 +1,32 @@ +using Furion; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Xunit; +using Xunit.Abstractions; +using Xunit.Sdk; +using Znyc.Dispatching.Core; + +// 配置启动类类型,第一个参数是 Startup 类完整限定名,第二个参数是当前项目程序集名称 +[assembly: TestFramework("Znyc.Dispatching.Tests.Startup", "Znyc.Dispatching.Tests")] + +namespace Znyc.Dispatching.Tests +{ + /// + /// 单元测试启动类 + /// + /// 在这里可以使用 Furion 几乎所有功能 + public sealed class Startup : XunitTestFramework + { + public Startup(IMessageSink messageSink) : base(messageSink) + { + // 初始化 IServiceCollection 对象 + IServiceCollection services = Inject.Create(); + + services.AddScoped(); + services.TryAddSingleton(); + // 构建 ServiceProvider 对象 + services.Build(); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatchimg.Test/UnitTest1.cs b/src/Znyc.Dispatchimg.Test/UnitTest1.cs new file mode 100644 index 0000000..a3acb36 --- /dev/null +++ b/src/Znyc.Dispatchimg.Test/UnitTest1.cs @@ -0,0 +1,13 @@ +using Xunit; + +namespace Znyc.Dispatching.Tests +{ + public class UnitTest1 + { + [Fact] + public void Test1() + { + Assert.Equal(2, 1 + 1); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatchimg.Test/Znyc.Dispatching.Tests.csproj b/src/Znyc.Dispatchimg.Test/Znyc.Dispatching.Tests.csproj new file mode 100644 index 0000000..49b9cb3 --- /dev/null +++ b/src/Znyc.Dispatchimg.Test/Znyc.Dispatching.Tests.csproj @@ -0,0 +1,26 @@ + + + + net6.0 + false + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Cache/Services/CacheService.cs b/src/Znyc.Dispatching.Application/Cache/Services/CacheService.cs new file mode 100644 index 0000000..e5ba643 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Cache/Services/CacheService.cs @@ -0,0 +1,1235 @@ +using CSRedis; +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Mapster; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Cache; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.Application +{ + /// + /// 系统缓存服务 + /// + [ApiDescriptionSettings(Name = "cache", Order = 100)] + public class CacheService : ICacheService, IDynamicApiController, ITransient + { + private readonly IRepository _companyRepository; + private readonly IRepository _dictionaryRepository; + private readonly IRepository _employeeRepository; + private readonly IRedisCache _redisCache; + private readonly IRepository _vehicleRepository; + private readonly IRepository _yardRepository; + private readonly IRepository _userYardRepository; + private readonly IRepository _projectRepository; + private readonly IRepository _projectPersonRepository; + private readonly IRepository _orderRepository; + private readonly IRepository _vehiclePersonRepository; + private readonly IRepository _userRepository; + + public CacheService(IRedisCache redisCache, + IRepository vehicleRepository, + IRepository companyRepository, + IRepository dictionaryRepository, + IRepository yardRepository, + IRepository userYardRepository, + IRepository employeeRepository, + IRepository vehiclePersonRepositor, + IRepository projectPersonRepository, + IRepository projectRepository, + IRepository userRepository, + IRepository orderRepository) + { + _redisCache = redisCache; + _vehicleRepository = vehicleRepository; + _companyRepository = companyRepository; + _dictionaryRepository = dictionaryRepository; + _employeeRepository = employeeRepository; + _yardRepository = yardRepository; + _userYardRepository = userYardRepository; + _projectRepository = projectRepository; + _projectPersonRepository = projectPersonRepository; + _vehiclePersonRepository = vehiclePersonRepositor; + _userRepository = userRepository; + _orderRepository = orderRepository; + } + + #region 短信验证码 + + /// + /// 获取短信验证码缓存 + /// + /// + /// + [NonAction] + public async Task GetSmsCodeAsync(string phone) + { + string cacheKey = CommonConst.CACHE_KEY_CODE + $"{phone}"; + return await _redisCache.GetAsync(cacheKey); + } + + /// + /// 设置短信验证码缓存 + /// + /// + /// + /// + [NonAction] + public async Task SetSmsCodeAsync(string phone, string smsCode) + { + string cacheKey = CommonConst.CACHE_KEY_CODE + $"{phone}"; + return await _redisCache.SetAsync(cacheKey, smsCode, TimeSpan.FromMinutes(5)); + } + + /// + /// 删除短信验证码缓存 + /// + /// + /// + [NonAction] + public async Task RemoveSmsCodeAsync(string phone) + { + string cacheKey = CommonConst.CACHE_KEY_CODE + $"{phone}"; + await _redisCache.DelAsync(cacheKey); + } + + #endregion 短信验证码 + + #region 权限 + + /// + /// 获取权限缓存(按钮) + /// + /// + /// + [NonAction] + public async Task> GetPermissionAsync(long userId) + { + string cacheKey = CommonConst.CACHE_KEY_PERMISSION + $"{userId}"; + return await _redisCache.GetAsync>(cacheKey); + } + + /// + /// 缓存权限 + /// + /// + /// + /// + [NonAction] + public async Task SetPermissionAsync(long userId, List permissions) + { + string cacheKey = CommonConst.CACHE_KEY_PERMISSION + $"{userId}"; + await _redisCache.SetAsync(cacheKey, permissions); + } + + #endregion 权限 + + #region 车辆分组 + + /// + /// 同步车辆分组缓存 + /// + /// + /// + /// + [NonAction] + public async Task SetVehicleGroupListAsync(long companyId, List vehicleGroup) + { + string cacheKey = CommonConst.CACHE_KEY_PERMISSION + $"{companyId}"; + await _redisCache.SetAsync(cacheKey, vehicleGroup, TimeSpan.FromDays(31)); + } + + /// + /// 获取车辆分组缓存 + /// + /// + /// + [NonAction] + public async Task> GetVehicleGroupListAsync(long companyId) + { + string cacheKey = CommonConst.CACHE_KEY_PERMISSION + $"{companyId}"; + return await _redisCache.GetAsync>(cacheKey); + } + + /// + /// 同步车辆类型缓存 + /// + /// + /// + [NonAction] + public async Task SetVehicleTypeListAsync(List vehicleType) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLETYPE; + await _redisCache.SetAsync(cacheKey, vehicleType, TimeSpan.FromDays(33)); + } + + /// + /// 获取车辆分组缓存 + /// + /// + [NonAction] + public async Task> GetVehicleTypeListAsync() + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLETYPE; + + return await _redisCache.GetAsync>(cacheKey); + } + + #endregion 车辆分组 + + #region 角色菜单 + + /// + /// 同步角色菜单缓存 + /// + /// + /// + /// + [NonAction] + public async Task SetRoleMenuAsync(long roleId, List menuList) + { + string cacheKey = CommonConst.CACHE_KEY_ROLEMENU + $"{roleId}"; + await _redisCache.SetAsync(cacheKey, menuList, TimeSpan.FromDays(34)); + } + + /// + /// 获取角色菜单缓存 + /// + /// + [NonAction] + public async Task> GetRoleMenuAsync(long roleId) + { + string cacheKey = CommonConst.CACHE_KEY_ROLEMENU + $"{roleId}"; + + return await _redisCache.GetAsync>(cacheKey); + } + + /// + /// 删除角色菜单缓存 + /// + /// + /// + [NonAction] + public async Task RemoveRoleMenuAsync(long roleId) + { + string cacheKey = CommonConst.CACHE_KEY_ROLEMENU + $"{roleId}"; + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 同步角色缓存 + /// + /// + /// + [NonAction] + public async Task SetRoleAsync(List role) + { + string cacheKey = CommonConst.CACHE_KEY_ROLE; + await _redisCache.SetAsync(cacheKey, role, TimeSpan.FromDays(35)); + } + + /// + /// 获取角色缓存 + /// + /// + [NonAction] + public async Task> GetRoleAsync() + { + string cacheKey = CommonConst.CACHE_KEY_ROLE; + return await _redisCache.GetAsync>(cacheKey); + } + + #endregion 角色菜单 + + #region 字典类型 + + /// + /// 同步字典类型缓存 + /// + /// + /// + [NonAction] + public async Task SetDictionaryListAsync(List dictionaryLists) + { + string cacheKey = CommonConst.CACHE_KEY_DICTIONARY; + await _redisCache.SetAsync(cacheKey, dictionaryLists); + } + + /// + /// 获取字典缓存 + /// + /// + [NonAction] + public async Task> GetDictionaryListAsync() + { + string cacheKey = CommonConst.CACHE_KEY_DICTIONARY; + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(365).TotalSeconds, + () => _dictionaryRepository.DetachedEntities + .Where(x => x.IsEnabled == (int)CommonStatusEnum.ENABLE) + .OrderBy(x => x.Sort) + .Select(x => new DictionaryOutput + { + Id = x.Id, + Code = x.Code, + Value = x.Value, + Name = x.Name, + Sort = x.Sort + }) + .ToListAsync()); + } + + #endregion 字典类型 + + #region 公司 + + /// + /// 同步公司缓存 + /// + /// + /// + [NonAction] + public async Task SetComanyAsync(CompanyOutput company) + { + string cacheKey = CommonConst.CACHE_KEY_COMPANY + $"{company.Id}"; + await _redisCache.SetAsync(cacheKey, company, TimeSpan.FromDays(36)); + } + + /// + /// 获取公司缓存 + /// + /// + /// + /// + [NonAction] + public async Task GetCompanyAsync(long companyId, long userId) + { + string cacheKey = CommonConst.CACHE_KEY_COMPANY + $"{companyId}"; + //CompanyOutput companyOutput = await _redisCache.GetAsync(cacheKey); + var companyOutput = await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(30).TotalSeconds, + () => _companyRepository.Where(x => x.Id == companyId).Select(x => new CompanyOutput + { + Id = x.Id, + CompanyName = x.CompanyName, + Longitude = x.Longitude, + Latitude = x.Latitude, + Address = x.Address, + Status = x.Status, + StopTag = x.StopTag, + IsOpenDispatch = x.IsOpenDispatch, + IsSchedulingAddProject = x.IsSchedulingAddProject, + IsOpenVehicleType = x.IsOpenVehicleType + }).FirstOrDefaultAsync()); + if (companyOutput.IsNotNull()) + { + List yardList = await GetYardListAsync(companyId); + UserYard userYard = await _userYardRepository.DetachedEntities + .FirstOrDefaultAsync(x => x.UserId == userId && x.CompanyId == companyId && x.IsDefault == true); + List listOutputs = yardList.Adapt>(); + if (userYard.IsNotNull()) + { + foreach (var item in listOutputs) + { + if (item.Id == userYard.YardId) + { + item.IsDefault = true; + } + } + listOutputs = listOutputs.OrderByDescending(x => x.IsDefault).ToList(); + } + companyOutput.yardList = yardList.Count != 0 ? listOutputs : new List() { + new YardListOutput() + { + Id = 0, + Address = companyOutput.Address, + Latitude = companyOutput.Latitude, + Longitude = companyOutput.Longitude, + IsDefault = false + } + }; + } + return companyOutput; + } + + /// + /// 删除公司缓存 + /// + /// + /// + [NonAction] + public async Task RemoveCompanyAsync(long companyId) + { + string cacheKey = CommonConst.CACHE_KEY_COMPANY + $"{companyId}"; + await _redisCache.DelAsync(cacheKey); + } + + #endregion 公司 + + #region 用户 + + /// + /// 同步用户缓存 + /// + /// + /// + [NonAction] + public async Task SetUserAsync(UserOutput user) + { + string cacheKey = CommonConst.CACHE_KEY_USER + $"{user.Id}"; + await _redisCache.SetAsync(cacheKey, user, TimeSpan.FromDays(41)); + } + + /// + /// 获取用户缓存 + /// + /// + [NonAction] + public async Task GetUserAsync(long userId) + { + string cacheKey = CommonConst.CACHE_KEY_USER + $"{userId}"; + var userOutput = await _redisCache.GetAsync(cacheKey); + return userOutput; + } + + /// + /// 移除用户缓存 + /// + /// + /// + [NonAction] + public async Task RemoveUserAsync(long userId) + { + string cacheKey = CommonConst.CACHE_KEY_USER + $"{userId}"; + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 删除用户所有缓存 + /// + /// + [NonAction] + public async Task RemoveCacheByUserIdAsync(long userId) + { + await RemoveUserAsync(userId); + await RemoveCompanyAsync(userId); + await RemoveTokenAsync(userId); + } + + #endregion 用户 + + #region Token + + /// + /// 写入token + /// + /// + /// + /// + [NonAction] + public async Task SetTokenAsync(long userId, string token) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_TOKEN, userId); + await _redisCache.SetAsync(cacheKey, token, TimeSpan.FromDays(60)); + } + + /// + /// 移除token + /// + /// + /// + [NonAction] + public async Task RemoveTokenAsync(long userId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_TOKEN, userId); + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取token + /// + /// + /// + [NonAction] + public async Task GetTokenAsync(long userId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_TOKEN, userId); + return await _redisCache.GetAsync(cacheKey); + } + + #endregion Token + + #region 公司车辆 + + /// + /// 设置公司车辆缓存 + /// + /// + /// + /// + [NonAction] + public async Task SetVehicleByCompanyIdAsync(long companyId, List vehicles) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLEBYCOMPANYID + $"{companyId}"; + await _redisCache.SetAsync(cacheKey, vehicles, TimeSpan.FromDays(7)); + } + + /// + /// 删除公司车辆缓存 + /// + /// + /// + [NonAction] + public async Task RemoveVehicleByCompanyIdAsync(long companyId) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLEBYCOMPANYID + $"{companyId}"; + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 删除公司车辆缓存 + /// + /// + /// + [NonAction] + public async Task RemoveAllVehicleByCompanyIdAsync() + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLEBYCOMPANYID + $"*"; + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取公司车辆缓存 + /// + /// + /// + [NonAction] + public async Task> GetVehicleByCompanyIdAsync(long companyId) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLEBYCOMPANYID + $"{companyId}"; + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(60).TotalSeconds, () => + _vehicleRepository + .Where(x => x.CompanyId == companyId) + .Select(x => new VehicleGpsOutput + { + Id = x.Id, + CompanyId = x.CompanyId, + VehiclePlate = x.VehiclePlate, + VehicleCode = x.VehicleCode, + ContactPerson = x.ContactPerson, + ContactPhone = x.ContactPhone, + Status = x.Status, + IsActivate = x.IsActivate, + IsGps = x.IsGps, + SimNo = x.SimNo, + IsOverspeedAlarm = x.IsOverspeedAlarm, + Overspeed = x.Overspeed, + ImeiNo = x.ImeiNo, + OpenTime = x.OpenTime, + ExpireTime = x.ExpireTime, + Sort = x.Sort, + }) + .OrderBy(x => x.Sort) + .ToListAsync()); + } + + /// + /// 获取公司车辆缓存 + /// + /// + /// + [NonAction] + public async Task> GetAllVehicleByCompanyIdAsync() + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLEBYCOMPANYID + $"*"; + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(1).TotalSeconds, () => + _vehicleRepository + .Where(x => x.CompanyId != 0) + .Select(x => new VehicleGpsOutput + { + Id = x.Id, + CompanyId = x.CompanyId, + VehiclePlate = x.VehiclePlate, + VehicleCode = x.VehicleCode, + ContactPerson = x.ContactPerson, + ContactPhone = x.ContactPhone, + Status = x.Status, + IsActivate = x.IsActivate, + IsGps = x.IsGps, + SimNo = x.SimNo, + IsOverspeedAlarm = x.IsOverspeedAlarm, + Overspeed = x.Overspeed, + ImeiNo = x.ImeiNo, + OpenTime = x.OpenTime, + ExpireTime = x.ExpireTime, + Sort = x.Sort, + }) + .OrderBy(x => x.Sort) + .ToListAsync()); + } + + + + #endregion 公司车辆 + + #region 车辆 + + /// + /// 设置车辆缓存 + /// + /// + /// + [NonAction] + public async Task SetVehicleAsync(Vehicle vehicle) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLE + $"{vehicle.Id}"; + await _redisCache.SetAsync(cacheKey, vehicle, TimeSpan.FromDays(8)); + } + + /// + /// 删除车辆缓存 + /// + /// + /// + [NonAction] + public async Task RemoveVehicleAsync(long vehicleId) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLE + $"{vehicleId}"; + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取车辆缓存 + /// + /// + /// + [NonAction] + public async Task GetVehicleAsync(long vehicleId) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLE + $"{vehicleId}"; + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(90).TotalSeconds, + () => _vehicleRepository.Where(x => x.Id == vehicleId).FirstOrDefaultAsync()); + } + + + #endregion 车辆 + + #region 员工 + + /// + /// 设置员工缓存 + /// + /// + /// + [NonAction] + public async Task SetEmployeeAsync(EmployeeOutput employee) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_EMPLOYEE, employee.Id); + await _redisCache.SetAsync(cacheKey, employee, TimeSpan.FromDays(11)); + } + + /// + /// 删除员工缓存 + /// + /// + /// + [NonAction] + public async Task RemoveEmployeeAsync(long employeeId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_EMPLOYEE, employeeId); + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取员工缓存 + /// + /// + /// + [NonAction] + public async Task GetEmployeeAsync(long employeeId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_EMPLOYEE, employeeId); + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(90).TotalSeconds, () => + _employeeRepository.Where(x => x.Id == employeeId).Select(x => new EmployeeOutput + { + Id = x.Id, + UserId = x.UserId, + AvatarUrl = x.AvatarUrl, + RoleId = x.RoleId, + RoleName = x.RoleName, + CompanyId = x.CompanyId, + EmployeeName = x.EmployeeName, + EmployeePhone = x.EmployeePhone, + Status = x.Status + }).FirstOrDefaultAsync()); + } + + /// + /// 设置员工列表缓存 + /// + /// + /// + /// + [NonAction] + public async Task SetEmployeeListAsync(long companyId, List employees) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_EMPLOYEES, companyId); + await _redisCache.SetAsync(cacheKey, employees, TimeSpan.FromDays(13)); + } + + /// + /// 删除员工列表缓存 + /// + /// + /// + [NonAction] + public async Task RemoveEmployeeListAsync(long companyId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_EMPLOYEES, companyId); + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取员工列表缓存 + /// + /// + /// + [NonAction] + public async Task> GetEmployeeListAsync(long companyId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_EMPLOYEES, companyId); + + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(95).TotalSeconds, () => + _employeeRepository.DetachedEntities + .Where(x => x.CompanyId == companyId + && x.IsDeleted == false) + .Select(x => new EmployeeOutput + { + Id = x.Id, + UserId = x.UserId, + RoleId = x.RoleId, + RoleName = x.RoleName, + CompanyId = x.CompanyId, + EmployeeName = x.EmployeeName, + EmployeePhone = x.EmployeePhone, + Status = x.Status + }).ToListAsync()); + } + + public async Task PublishAsync(string channel, string message) + { + return await _redisCache.PublishAsync(channel, message); + } + + public CSRedisClient.SubscribeObject Subscribe( + params (string, Action)[] channels) + { + return _redisCache.Subscribe(channels); + } + + #endregion 员工 + + #region 未读警报提醒 + + /// + /// 设置未读警报提醒缓存 + /// + /// + /// + public async Task SetUnreadAlarmAsync(long userId) + { + string key = string.Format(CommonConst.CACHE_KEY_UNREADALARM, userId); + await _redisCache.SetAsync(key, DateTime.Now, TimeSpan.FromDays(5)); + } + + /// + /// 删除未读警报提醒缓存 + /// + /// + /// + public async Task RemoveUnreadAlarmAsync(long userId) + { + string key = string.Format(CommonConst.CACHE_KEY_UNREADALARM, userId); + await _redisCache.DelAsync(key); + } + + /// + /// 获取未读警报提醒缓存 + /// + /// + public async Task GetUnreadAlarmAsync(long userId) + { + string key = string.Format(CommonConst.CACHE_KEY_UNREADALARM, userId); + return await _redisCache.GetAsync(key); + } + + #endregion + + #region 轨迹回放 + /// + /// 同步轨迹回放缓存 + /// + /// + /// + /// + /// + /// + /// + public async Task SeTrackPlaybackAsync(TrackPlaybackListOutput trackPlaybackListOutput, long vehicleId, DateTime startTime, DateTime endTime, TimeSpan expire) + { + string cacheKey = CommonConst.CACHE_KEY_TRACKPLAYBACK + $"{vehicleId}{startTime.ToTimestamp()}{endTime.ToTimestamp()}"; + await _redisCache.SetAsync(cacheKey, trackPlaybackListOutput, expire); + } + + /// + /// 获取轨迹回放缓存 + /// + /// + /// + /// + /// + public async Task GetTrackPlaybackAsync(long vehicleId, DateTime startTime, DateTime endTime) + { + string cacheKey = CommonConst.CACHE_KEY_TRACKPLAYBACK + $"{vehicleId}{startTime.ToTimestamp()}{endTime.ToTimestamp()}"; + return await _redisCache.GetAsync(cacheKey); + + } + + /// + /// 删除轨迹回放缓存 + /// + /// + /// + /// + /// + public async Task RemoveTrackPlaybackAsync(long vehicleId, DateTime startTime, DateTime endTime) + { + string cacheKey = CommonConst.CACHE_KEY_TRACKPLAYBACK + $"{vehicleId}{startTime.ToTimestamp()}{endTime.ToTimestamp()}"; + await _redisCache.DelAsync(cacheKey); + } + #endregion + + #region 车场 + /// + /// 设置车场缓存 + /// + /// + /// + [NonAction] + public async Task SetYardAsync(YardOutput yard) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_YARD, yard.Id); + await _redisCache.SetAsync(cacheKey, yard, TimeSpan.FromDays(11)); + } + + /// + /// 删除车场缓存 + /// + /// + /// + [NonAction] + public async Task RemoveYardAsync(long yardId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_YARD, yardId); + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取车场缓存 + /// + /// + /// + [NonAction] + public async Task GetYardAsync(long yardId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_YARD, yardId); + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(90).TotalSeconds, () => + _yardRepository.Where(x => x.Id == yardId).Select(x => new YardOutput + { + Id = x.Id, + ContactPerson = x.ContactPerson, + ContactPhone = x.ContactPhone, + IsDefault = false, + Latitude = x.Latitude, + Longitude = x.Longitude, + Address = x.Address, + }).FirstOrDefaultAsync()); + } + + /// + /// 设置车场列表缓存 + /// + /// + /// + /// + [NonAction] + public async Task SetYardListAsync(long companyId, List yards) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_YARDS, companyId); + await _redisCache.SetAsync(cacheKey, yards, TimeSpan.FromDays(13)); + } + + /// + /// 删除车场列表缓存 + /// + /// + /// + [NonAction] + public async Task RemoveYardListAsync(long companyId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_YARDS, companyId); + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取车场列表缓存 + /// + /// + /// + [NonAction] + public async Task> GetYardListAsync(long companyId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_YARDS, companyId); + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(95).TotalSeconds, () => + _yardRepository.DetachedEntities + .Where(x => x.CompanyId == companyId && x.Status == (int)CommonStatusEnum.ENABLE) + .Select(x => new YardOutput + { + Id = x.Id, + ContactPerson = x.ContactPerson, + ContactPhone = x.ContactPhone, + IsDefault = false, + Latitude = x.Latitude, + Longitude = x.Longitude, + Address = x.Address, + Status = x.Status + }).ToListAsync()); + } + #endregion + + #region 工程信息 + /// + /// 同步工程列表缓存 + /// + /// + /// + /// + [NonAction] + public async Task SetProjectListAsync(List projects, long companyId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_PROJECTS, companyId); + await _redisCache.SetAsync(cacheKey, projects, TimeSpan.FromDays(15)); + } + + /// + /// 获取工程列表缓存 + /// + /// + /// + [NonAction] + public async Task> GetProjectListAsync(long companyId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_PROJECTS, companyId); + var projectOutput = await _redisCache.GetAsync>(cacheKey); + if (projectOutput.IsNull()) + { + projectOutput = await _projectRepository.DetachedEntities + .Where(x => x.IsDeleted == false && x.CompanyId == companyId) + .Select(x => new ProjectListOutput + { + Id = x.Id, + ProjectName = x.ProjectName, + SalesmanId = x.SalesmanId, + Address = x.Address, + Latitude = x.Latitude, + Longitude = x.Longitude, + IsEnabled = x.IsEnabled, + ConstructionId = x.ConstructionId + }).ToListAsync(); + long[] projectIds = projectOutput.Select(x => x.Id).Distinct().ToArray(); + List projectPersons = await _projectPersonRepository.DetachedEntities + .Where(x => projectIds.Contains(x.ProjectId) && x.IsDeleted == false) + .ToListAsync(); + projectOutput.ForEach(item => + { + item.ProjectPeoples = projectPersons.Where(x => x.ProjectId == item.Id).Select(x => new ProjectPersonOutput + { + ProjectPersonId = x.ProjectPersonId, + ProjectPersonName = x.ProjectPersonName, + ProjectPersonPhone = x.ProjectPersonPhone + }).ToList(); + }); + await SetProjectListAsync(projectOutput, companyId); + } + + return projectOutput; + } + + /// + /// 删除工程列表缓存 + /// + /// + /// + [NonAction] + public async Task RemoveProjectListAsync(long companyId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_PROJECTS, companyId); + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 设置工程缓存 + /// + /// + /// + [NonAction] + public async Task SetProjectAsync(ProjectOutput project) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_PROJECT, project.Id); + await _redisCache.SetAsync(cacheKey, project, TimeSpan.FromDays(11)); + } + + /// + /// 删除工程缓存 + /// + /// + /// + [NonAction] + public async Task RemoveProjectAsync(long projectId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_PROJECT, projectId); + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取工程缓存 + /// + /// + /// + [NonAction] + public async Task GetProjectAsync(long projectId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_PROJECT, projectId); + List projectPeoples = await _projectPersonRepository.DetachedEntities + .Where(x => x.ProjectId == projectId && x.IsDeleted == false) + .Select(x => new ProjectPersonOutput + { + ProjectPersonId = x.ProjectPersonId, + ProjectPersonName = x.ProjectPersonName, + ProjectPersonPhone = x.ProjectPersonPhone + }).ToListAsync(); + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(90).TotalSeconds, () => + _projectRepository.Where(x => x.Id == projectId).Select(x => new ProjectOutput + { + Id = x.Id, + ProjectName = x.ProjectName, + SalesmanId = x.SalesmanId, + Longitude = x.Longitude, + Latitude = x.Latitude, + Address = x.Address, + IsEnabled = x.IsEnabled, + ProjectPeoples = projectPeoples, + ConstructionId = x.ConstructionId, + ConstructionName = x.ConstructionName + }).FirstOrDefaultAsync()); + } + + #endregion + + + + #region 订单 + + /// + /// 设置订单列表缓存 + /// + /// + /// + /// + [NonAction] + public async Task SetOrderListAsync(long companyId, List orders) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_EMPLOYEES, companyId); + await _redisCache.SetAsync(cacheKey, orders, TimeSpan.FromDays(5)); + } + + /// + /// 删除订单列表缓存 + /// + /// + /// + [NonAction] + public async Task RemoveOrderListAsync(long companyId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_ORDERS, companyId); + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取订单列表缓存 + /// + /// + /// + [NonAction] + public async Task> GetOrderListAsync(long companyId) + { + string cacheKey = string.Format(CommonConst.CACHE_KEY_ORDERS, companyId); + + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(30).TotalSeconds, () => + _orderRepository.DetachedEntities + .Where(x => x.CompanyId == companyId) + .Select(x => new OrderListOutput + { + OrderSourceName = "222" + //RoleId = x.RoleId, + //RoleName = x.RoleName, + //CompanyId = x.CompanyId, + //EmployeeName = x.EmployeeName, + //OrderContent = x.or + }).ToListAsync()); + } + #endregion + + #region 车组人员 + /// + /// 设置车辆车组人员缓存 + /// + /// + /// + /// + [NonAction] + public async Task SetVehiclePersonAsync(List vehiclePerson, long vehicleId) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLEPERSON + $"{vehicleId}"; + await _redisCache.SetAsync(cacheKey, vehiclePerson, TimeSpan.FromDays(8)); + } + + /// + /// 删除车辆车组人员缓存 + /// + /// + /// + [NonAction] + public async Task RemoveVehiclePersonAsync(long vehicleId) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLEPERSON + $"{vehicleId}"; + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取车辆车组人员缓存 + /// + /// + /// + [NonAction] + public async Task> GetVehiclePersonAsync(long vehicleId) + { + string cacheKey = CommonConst.CACHE_KEY_VEHICLEPERSON + $"{vehicleId}"; + return await _redisCache.CacheShellAsync(cacheKey, (int)TimeSpan.FromDays(90).TotalSeconds, + () => _vehiclePersonRepository.Where(x => x.IsDeleted == false).Select(x => new VehiclePersonOutput + { + Id = x.Id, + VehicleId = x.VehicleId, + UserId = x.UserId, + UserName = x.UserName, + UserPhone = x.UserPhone, + IsDriver = x.IsDriver + }).Where(x => x.VehicleId == vehicleId).ToListAsync()); + } + + #endregion + + + #region Order + /// + /// 设置缓存 + /// + /// + /// + /// + public async Task SetVehicleGpsAsync(long orderId, dynamic clay) + { + string cacheKey = CommonConst.CACHE_KEY_GPSREALTIME + $"{orderId}"; + await _redisCache.SetAsync(cacheKey, clay, TimeSpan.FromDays(1)); + + } + + /// + /// 删除缓存 + /// + /// + /// + public async Task RemoveVehicleGpsAsync(long orderId) + { + string cacheKey = CommonConst.CACHE_KEY_GPSREALTIME + $"{orderId}"; + await _redisCache.DelAsync(cacheKey); + + } + + /// + /// 获取缓存 + /// + /// + /// + public async Task GetVehicleGpsAsync(long orderId) + { + string cacheKey = CommonConst.CACHE_KEY_GPSREALTIME + $"{orderId}"; + return await _redisCache.GetAsync(cacheKey); + } + #endregion + + + + /// + /// 设置缓存 + /// + /// + /// + public async Task SetOrderReadAsync(long orderId, string messageType) + { + string cacheKey = CommonConst.CACHE_KEY_ORDERREAD + $"{orderId}"; + await _redisCache.SetAsync(cacheKey, messageType); + } + + /// + /// 删除缓存 + /// + /// + /// + public async Task RemoveOrderReadAsync(long orderId) + { + string cacheKey = CommonConst.CACHE_KEY_ORDERREAD + $"{orderId}"; + await _redisCache.DelAsync(cacheKey); + } + + /// + /// 获取缓存 + /// + /// + /// + public async Task GetOrderReadAsync(long orderId) + { + string cacheKey = CommonConst.CACHE_KEY_ORDERREAD + $"{orderId}"; + return await _redisCache.GetAsync(cacheKey); + } + + /// + /// 获取缓存 + /// + /// + /// + public async Task ExistsOrderReadAsync(long orderId) + { + string cacheKey = CommonConst.CACHE_KEY_ORDERREAD + $"{orderId}"; + return await _redisCache.ExistsAsync(cacheKey); + } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Cache/Services/ICacheService.cs b/src/Znyc.Dispatching.Application/Cache/Services/ICacheService.cs new file mode 100644 index 0000000..d6375ab --- /dev/null +++ b/src/Znyc.Dispatching.Application/Cache/Services/ICacheService.cs @@ -0,0 +1,554 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.MongoDb.Repository.Collection; +using static CSRedis.CSRedisClient; + +namespace Znyc.Dispatching.Application +{ + public interface ICacheService + { + /// + /// 获取短信验证码 + /// + /// + /// + Task GetSmsCodeAsync(string phone); + + /// + /// 设置验证码缓存 + /// + /// + /// + /// + Task SetSmsCodeAsync(string phone, string smsCode); + + /// + /// 删除验证码 + /// + /// + /// + Task RemoveSmsCodeAsync(string phone); + + /// + /// 获取权限缓存(按钮) + /// + /// + /// + Task> GetPermissionAsync(long userId); + + /// + /// 缓存权限 + /// + /// + /// + /// + Task SetPermissionAsync(long userId, List permissions); + + /// + /// 同步车辆分组缓存 + /// + /// + /// + /// + Task SetVehicleGroupListAsync(long companyId, List vehicleGroup); + + /// + /// 获取车辆分组缓存 + /// + /// + /// + Task> GetVehicleGroupListAsync(long companyId); + + /// + /// 同步车辆类型缓存 + /// + /// + /// + Task SetVehicleTypeListAsync(List vehicleType); + + /// + /// 获取车辆类型缓存 + /// + /// + Task> GetVehicleTypeListAsync(); + + /// + /// 同步角色菜单缓存 + /// + /// + /// + /// + Task SetRoleMenuAsync(long roleId, List menuList); + + /// + /// 获取角色菜单缓存 + /// + /// + /// + Task> GetRoleMenuAsync(long roleId); + + /// + /// 删除角色菜单缓存 + /// + /// + /// + Task RemoveRoleMenuAsync(long roleId); + + /// + /// 同步角色缓存 + /// + /// + /// + Task SetRoleAsync(List role); + + /// + /// 获取角色缓存 + /// + /// + Task> GetRoleAsync(); + + /// + /// 获取字典缓存 + /// + /// + Task> GetDictionaryListAsync(); + + /// + /// 同步字典缓存 + /// + /// + /// + Task SetDictionaryListAsync(List dictionaryLists); + + /// + /// 同步公司缓存 + /// + /// + /// + Task SetComanyAsync(CompanyOutput company); + + /// + /// 获取公司缓存 + /// + /// + /// + /// + Task GetCompanyAsync(long companyId, long userId); + + /// + /// 删除公司缓存 + /// + /// + /// + Task RemoveCompanyAsync(long companyId); + + /// + /// 同步用户缓存 + /// + /// + /// + Task SetUserAsync(UserOutput user); + + /// + /// 获取用户缓存 + /// + /// + /// + Task GetUserAsync(long userId); + + /// + /// 移除用户缓存 + /// + /// + /// + Task RemoveUserAsync(long userId); + + /// + /// 删除用户所有缓存 + /// + /// + Task RemoveCacheByUserIdAsync(long userId); + + /// + /// 写入token + /// + /// + /// + /// + Task SetTokenAsync(long userId, string token); + + /// + /// 移除token + /// + /// + /// + Task RemoveTokenAsync(long userId); + + /// + /// 获取token + /// + /// + /// + Task GetTokenAsync(long userId); + + + /// + /// 发布 + /// + /// + /// + /// + Task PublishAsync(string channel, string message); + + + /// + /// 订阅 + /// + /// + /// + SubscribeObject Subscribe(params (string, Action)[] channels); + + #region 公司车辆 + + /// + /// 设置公司车辆缓存 + /// + /// + /// + /// + Task SetVehicleByCompanyIdAsync(long companyId, List vehicles); + + /// + /// 删除公司车辆缓存 + /// + /// + /// + Task RemoveVehicleByCompanyIdAsync(long companyId); + + + /// + /// 删除公司车辆缓存 + /// + /// + /// + Task RemoveAllVehicleByCompanyIdAsync(); + + + /// + /// 获取所有公司车辆缓存 + /// + /// + /// + Task> GetAllVehicleByCompanyIdAsync(); + + /// + /// 获取公司车辆缓存 + /// + /// + /// + Task> GetVehicleByCompanyIdAsync(long companyId); + + #endregion 公司车辆 + + #region 车辆 + + /// + /// 设置车辆缓存 + /// + /// + /// + Task SetVehicleAsync(Vehicle vehicle); + + /// + /// 删除车辆缓存 + /// + /// + /// + Task RemoveVehicleAsync(long vehicleId); + + /// + /// 获取车辆缓存 + /// + /// + /// + Task GetVehicleAsync(long vehicleId); + + #endregion 车辆 + + #region 员工 + + /// + /// 设置车辆缓存 + /// + /// + /// + Task SetEmployeeAsync(EmployeeOutput employee); + + /// + /// 删除员工缓存 + /// + /// + /// + Task RemoveEmployeeAsync(long employeeId); + + /// + /// 获取员工缓存 + /// + /// + /// + Task GetEmployeeAsync(long employeeId); + + /// + /// 设置员工列表缓存 + /// + /// + /// + /// + Task SetEmployeeListAsync(long companyId, List employees); + + /// + /// 删除员工列表缓存 + /// + /// + /// + Task RemoveEmployeeListAsync(long companyId); + + /// + /// 获取员工列表缓存 + /// + /// + /// + Task> GetEmployeeListAsync(long companyId); + + #endregion 员工 + + #region 未读警报提醒 + + /// + /// 设置未读警报提醒缓存 + /// + /// + /// + Task SetUnreadAlarmAsync(long userId); + + /// + /// 删除未读警报提醒缓存 + /// + /// + /// + Task RemoveUnreadAlarmAsync(long userId); + + /// + /// 获取未读警报提醒缓存 + /// + /// + Task GetUnreadAlarmAsync(long userId); + + #endregion + + #region 轨迹回放 + /// + /// 同步轨迹回放缓存 + /// + /// + /// + /// + /// + /// + /// + Task SeTrackPlaybackAsync(TrackPlaybackListOutput trackPlaybackListOutput, long vehicleId, DateTime startTime, DateTime endTime, TimeSpan expire); + + /// + /// 获取轨迹回放缓存 + /// + /// + /// + /// + /// + Task GetTrackPlaybackAsync(long vehicleId, DateTime startTime, DateTime endTime); + + /// + /// 删除轨迹回放缓存 + /// + /// + /// + /// + /// + Task RemoveTrackPlaybackAsync(long vehicleId, DateTime startTime, DateTime endTime); + #endregion + + #region 车场 + /// + /// 设置车场缓存 + /// + /// + /// + Task SetYardAsync(YardOutput yard); + + /// + /// 删除车场缓存 + /// + /// + /// + Task RemoveYardAsync(long yardId); + + /// + /// 获取车场缓存 + /// + /// + /// + Task GetYardAsync(long yardId); + + /// + /// 设置车场列表缓存 + /// + /// + /// + /// + Task SetYardListAsync(long companyId, List yards); + + /// + /// 删除车场列表缓存 + /// + /// + /// + Task RemoveYardListAsync(long companyId); + + /// + /// 获取车场列表缓存 + /// + /// + /// + Task> GetYardListAsync(long companyId); + #endregion + + + #region 工程信息 + /// + /// 同步工程列表缓存 + /// + /// + /// + /// + Task SetProjectListAsync(List projects, long companyId); + + /// + /// 获取工程列表缓存 + /// + /// + /// + Task> GetProjectListAsync(long companyId); + + /// + /// 删除工程列表缓存 + /// + /// + /// + Task RemoveProjectListAsync(long companyId); + + /// + /// 设置工程缓存 + /// + /// + /// + Task SetProjectAsync(ProjectOutput project); + + /// + /// 删除工程缓存 + /// + /// + /// + Task RemoveProjectAsync(long projectId); + + /// + /// 获取工程缓存 + /// + /// + /// + Task GetProjectAsync(long projectId); + #endregion + + #region 车组人员 + /// + /// 设置车辆车组人员缓存 + /// + /// + /// + /// + Task SetVehiclePersonAsync(List vehiclePerson, long vehicleId); + + /// + /// 删除车辆车组人员缓存 + /// + /// + /// + Task RemoveVehiclePersonAsync(long vehicleId); + + /// + /// 获取车辆车组人员缓存 + /// + /// + /// + Task> GetVehiclePersonAsync(long vehicleId); + + #endregion + + #region Order + /// + /// 设置缓存 + /// + /// + /// + /// + Task SetVehicleGpsAsync(long orderId, dynamic clay); + + /// + /// 删除缓存 + /// + /// + /// + Task RemoveVehicleGpsAsync(long orderId); + + /// + /// 获取缓存 + /// + /// + /// + Task GetVehicleGpsAsync(long orderId); + + + /// + /// 设置缓存 + /// + /// + /// + /// + Task SetOrderReadAsync(long orderId, string messageType); + + /// + /// 删除缓存 + /// + /// + /// + Task RemoveOrderReadAsync(long orderId); + + /// + /// 获取缓存 + /// + /// + /// + Task GetOrderReadAsync(long orderId); + + + + /// + /// 是否存在 + /// + /// + /// + Task ExistsOrderReadAsync(long orderId); + #endregion + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Company/Dto/Input/CompanyAddInput.cs b/src/Znyc.Dispatching.Application/Company/Dto/Input/CompanyAddInput.cs new file mode 100644 index 0000000..3008b70 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Company/Dto/Input/CompanyAddInput.cs @@ -0,0 +1,59 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// 公司输入实体 + /// + public class CompanyAddInput + { + /// + /// 公司名称 + /// + [Required(ErrorMessage = "公司名称不能为空!")] + [MaxLength(18, ErrorMessage = "公司名称不得超过18个字")] + public string CompanyName { get; set; } + + ///// + ///// 公司Logo + ///// + // public string CompanyLogo { get; set; } + + /// + /// 联系人 + /// + [MaxLength(8, ErrorMessage = "联系人不得超过8个字")] + public string ContactPerson { get; set; } + + /// + /// 联系人电话 + /// + //[Required(ErrorMessage = "联系人电话不能为空!"), MaxLength(11, ErrorMessage = "联系电话不能超过11位")] + //[RegularExpression("^[1][3,4,5,6,7,8,9][0-9]{9}$", ErrorMessage = "请输入正确的手机号码")] + public string ContactPhone { get; set; } + + /// + /// 精度 + /// + [Required(ErrorMessage = "地址不能为空!")] + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + [Required(ErrorMessage = "地址不能为空!")] + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + [Required(ErrorMessage = "地址不能为空!")] + [MaxLength(35, ErrorMessage = "地址不得超过35个字")] + public string Address { get; set; } + + /// + /// OpenId + /// + public string JsCode { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Company/Dto/Input/CompanyUpdateInput.cs b/src/Znyc.Dispatching.Application/Company/Dto/Input/CompanyUpdateInput.cs new file mode 100644 index 0000000..1b6b05e --- /dev/null +++ b/src/Znyc.Dispatching.Application/Company/Dto/Input/CompanyUpdateInput.cs @@ -0,0 +1,9 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class CompanyUpdateInput : CompanyAddInput + { + public long Id { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Company/Dto/Input/RegisterInuput.cs b/src/Znyc.Dispatching.Application/Company/Dto/Input/RegisterInuput.cs new file mode 100644 index 0000000..e996f2d --- /dev/null +++ b/src/Znyc.Dispatching.Application/Company/Dto/Input/RegisterInuput.cs @@ -0,0 +1,61 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// 平台入驻 + /// + public class RegisterInuput + { + + /// + /// JsCode + /// + public string JsCode { get; set; } + + /// + /// 用户名 + /// + [MaxLength(8, ErrorMessage = "用户名不得超过8个字")] + public string UserName { get; set; } + + /// + /// 头像 + /// + public string AvatarUrl { get; set; } + + /// + /// 手机号 + /// + [MaxLength(11, ErrorMessage = "手机号输入格式不正确")] + public string Phone { get; set; } + + + /// + /// 公司名称 + /// + [Required(ErrorMessage = "公司名称不能为空!")] + [MaxLength(18, ErrorMessage = "公司名称不得超过18个字")] + public string CompanyName { get; set; } + + + /// + /// 精度 + /// + [Required(ErrorMessage = "地址不能为空!")] + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + [Required(ErrorMessage = "地址不能为空!")] + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + [Required(ErrorMessage = "地址不能为空!")] + [MaxLength(35, ErrorMessage = "地址不得超过35个字")] + public string Address { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Application/Company/Dto/OutPut/CompanyOutput.cs b/src/Znyc.Dispatching.Application/Company/Dto/OutPut/CompanyOutput.cs new file mode 100644 index 0000000..81b5fd9 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Company/Dto/OutPut/CompanyOutput.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class CompanyOutput + { + /// + /// 主键 + /// + public long Id { get; set; } + + /// + /// 公司名称 + /// + public string CompanyName { get; set; } + + /// + /// 公司Logo + /// + public string CompanyLogo { get; set; } + + /// + /// 精度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 状态(字典 0正常 1停用 2删除) + /// + public int Status { get; set; } + + /// + /// 停留标示Id + /// + public long StopTag { get; set; } + + /// + /// 车场 + /// + public List yardList { get; set; } + + + #region #v1.2.3 + + + /// + /// 一键派工是否显示工程名称 + /// + public bool IsOpenDispatch { get; set; } + + + /// + /// 调度角色是否有添 加工程名称的权限 + /// + public bool IsSchedulingAddProject { get; set; } + + #endregion + + + + #region v1.2.7 + + /// + /// 是否启用任务车型选项,默认为关 + /// + public bool IsOpenVehicleType { get; set; } + + #endregion + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Company/Services/CompanyService.cs b/src/Znyc.Dispatching.Application/Company/Services/CompanyService.cs new file mode 100644 index 0000000..8f4f6f1 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Company/Services/CompanyService.cs @@ -0,0 +1,307 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Mapster; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Helpers; + +namespace Znyc.Dispatching.Application +{ + /// + /// 公司服务 + /// + [ApiDescriptionSettings(Name = "company", Order = 30)] + public class CompanyService : ICompanyService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _employeeRepository; + private readonly IRepository _repository; + private readonly IUserManager _userManager; + private readonly IRepository _userRepository; + private readonly IRepository _vehicleGroupRepository; + private readonly WeixinSettingOptions _weixinSettingOptions; + private readonly IRepository _yardRepository; + private readonly IRepository _userYardRepository; + + public CompanyService( + IRepository repository, + IRepository employeeRepository, + IRepository userRepository, + IRepository vehicleGroupRepository, + IUserManager userManager, + ICacheService cacheService, + IRepository yardRepository, + IOptions weixinSettingOptions, + IRepository userYardRepository + ) + { + _employeeRepository = employeeRepository; + _userRepository = userRepository; + _vehicleGroupRepository = vehicleGroupRepository; + _repository = repository; + _userManager = userManager; + _cacheService = cacheService; + _yardRepository = yardRepository; + _weixinSettingOptions = weixinSettingOptions.Value; + _userYardRepository = userYardRepository; + } + + + + /// + /// 获取当前公司信息 + /// + /// + [HttpGet] + [Route("api/v1/company")] + public async Task GetAsync() + { + return await _cacheService.GetCompanyAsync(_userManager.CompanyId, _userManager.UserId); + } + + /// + /// 根据Id获取公司信息 + /// + /// + /// + [HttpGet] + [Route("api/v1/company/{companyId}")] + public async Task GetByIdAsync(long companyId) + { + return await _cacheService.GetCompanyAsync(companyId, _userManager.UserId); + } + + /// + /// 更新公司信息 + /// + /// + /// + [HttpPut] + [Route("api/v1/company")] + public async Task UpdateAsync(CompanyUpdateInput companyUpdate) + { + var company = await _repository.FindAsync(companyUpdate.Id); + if (company.IsNotNull()) + { + company.CompanyName = companyUpdate.CompanyName; + company.Latitude = companyUpdate.Latitude; + company.Longitude = companyUpdate.Longitude; + company.Address = companyUpdate.Address; + } + var companyId = (await _repository.UpdateNowAsync(company)).Entity.Id; + if (companyId == 0) + { + throw Oops.Bah("更新失败"); + } + await _cacheService.RemoveCompanyAsync(_userManager.CompanyId); + await _cacheService.RemoveUserAsync(_userManager.UserId); + } + + /// + /// 平台入驻 + /// + /// + /// + [AllowAnonymous] + [UnitOfWork] + [HttpPost] + [Route("api/v1/register")] + public async Task RegisterAsync(RegisterInuput registerInuput) + { + var jsCode2JsonResult = + await SnsApi.JsCode2JsonAsync(_weixinSettingOptions.WxOpenAppId, _weixinSettingOptions.WxOpenAppSecret, + registerInuput.JsCode); + if (jsCode2JsonResult.IsNull()) + { + throw Oops.Bah(ErrorCode.D1506); + } + var user = await _userRepository.FirstOrDefaultAsync(x => x.OpenId == jsCode2JsonResult.openid); + if (user.IsNotNull()) + { + var employeeList = await _employeeRepository.DetachedEntities + .Where(x => x.UserId == user.Id && x.Status == (int)CommonStatusEnum.ENABLE) + .ToListAsync(); + var cIds = employeeList.Select(x => x.CompanyId).ToArray(); + + //如果未包含管理员权限,可以一直注册 + if (employeeList.Where(x => x.RoleId == (long)RoleStatusEnum.Administrator && x.Status == (int)CommonStatusEnum.ENABLE).Any()) + { + throw Oops.Bah("您已注册公司"); + } + + } + + var entity = registerInuput.Adapt(); + entity.Status = (int)CommonStatusEnum.REVIEW; + entity.ContactPerson = registerInuput.UserName ?? "企业管理员"; + entity.ContactPhone = registerInuput.Phone; + entity.CompanyLogo = CommonConst.DEFAULT_AVATARURL; + entity.StopTag = CommonConst.DEFAULT_STAPTAG; + var companyId = (await _repository.InsertNowAsync(entity)).Entity.Id; + if (companyId > 0) + { + var userId = user.IsNull() ? 0 : user.Id; + if (user.IsNull()) + { + //用户 + userId = (await _userRepository.InsertNowAsync(new User + { + OpenId = jsCode2JsonResult.openid, + AvatarUrl = registerInuput.AvatarUrl, + UserName = registerInuput.UserName ?? "企业管理员", + Phone = registerInuput.Phone, + Status = CommonStatusEnum.ENABLE + })).Entity.Id; + } + //员工 + await _employeeRepository.InsertNowAsync(new Employee + { + UserId = userId, + AvatarUrl = CommonConst.DEFAULT_AVATARURL, + EmployeeName = registerInuput.UserName ?? "企业管理员", + EmployeePhone = registerInuput.Phone, + CompanyId = companyId, + RoleId = (int)RoleStatusEnum.Administrator, + RoleName = typeof(RoleStatusEnum).GetDescription((int)RoleStatusEnum.Administrator), + Status = (int)CommonStatusEnum.ENABLE, + IsDefault = true + }); + //车辆分组 + await _vehicleGroupRepository.InsertNowAsync(new VehicleGroup + { + CompanyId = companyId, + Name = "默认分组", + ParentId = 0 + }); + //车场 + var yardId = (await _yardRepository.InsertNowAsync(new Yard + { + CompanyId = companyId, + Status = (int)CommonStatusEnum.ENABLE, + ContactPerson = registerInuput.UserName ?? "企业管理员", + ContactPhone = registerInuput.Phone, + Longitude = registerInuput.Longitude, + Latitude = registerInuput.Latitude, + Address = registerInuput.Address, + + })).Entity.Id; + + //用户车场映射 + await _userYardRepository.InsertNowAsync(new UserYard + { + UserId = userId, + YardId = yardId, + CompanyId = companyId, + IsDefault = true + }); + } + } + + + /// + /// 获取位置名称 + /// + /// + /// + /// + [HttpGet] + [AllowAnonymous] + [Route("api/v1/address/{longitude}/{latitude}")] + public string GetAddress([Required] decimal longitude, [Required] decimal latitude) + { + string adress = MapHelper.GetLocationByLngLat(longitude, latitude); + return adress; + } + + /// + /// 修改公司停留标示 + /// + /// + /// + [HttpPut] + [Route("api/v1/company/stoptag/{stopTag}")] + public async Task UpdatStopTagAsync([Required] long stopTag) + { + var company = await _repository.FirstOrDefaultAsync(x => x.Id == _userManager.CompanyId); + if (company.IsNull()) + { + throw Oops.Bah("公司不存在"); + } + company.StopTag = stopTag; + await _repository.UpdateNowAsync(company); + await _cacheService.RemoveCompanyAsync(_userManager.CompanyId); + } + + + + + /// + /// 一键派工是否显示工程名称 + /// + /// + [HttpPut] + [Route("api/v1/company/opendispatch")] + public async Task UpdateIsOpenDispatchAsync() + { + var company = await _repository.FirstOrDefaultAsync(x => x.Id == _userManager.CompanyId); + if (company.IsNull()) + { + throw Oops.Bah("公司不存在"); + + } + company.IsOpenDispatch = !company.IsOpenDispatch; + await _repository.UpdateNowAsync(company); + await _cacheService.RemoveCompanyAsync(_userManager.CompanyId); + } + + + /// + /// 调度角色是否有添 加工程名称的权限 + /// + /// + [HttpPut] + [Route("api/v1/company/schedulingaddproject")] + public async Task UpdateIsSchedulingAddProjectAsync() + { + var company = await _repository.FirstOrDefaultAsync(x => x.Id == _userManager.CompanyId); + if (company.IsNull()) + { + throw Oops.Bah("公司不存在"); + + } + company.IsSchedulingAddProject = !company.IsSchedulingAddProject; + await _repository.UpdateNowAsync(company); + await _cacheService.RemoveCompanyAsync(_userManager.CompanyId); + } + + /// + /// + /// + /// + [HttpPut] + [Route("api/v1/company/isOpenVehicleType")] + public async Task UpdateIsOpenVehicleTypeAsync() + { + var company = await _repository.FirstOrDefaultAsync(x => x.Id == _userManager.CompanyId); + if (company.IsNull()) + { + throw Oops.Bah("公司不存在"); + + } + company.IsOpenVehicleType = !company.IsOpenVehicleType; + await _repository.UpdateNowAsync(company); + await _cacheService.RemoveCompanyAsync(_userManager.CompanyId); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Company/Services/ICompanyService.cs b/src/Znyc.Dispatching.Application/Company/Services/ICompanyService.cs new file mode 100644 index 0000000..82cc206 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Company/Services/ICompanyService.cs @@ -0,0 +1,68 @@ +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface ICompanyService + { + /// + /// 注册公司 + /// + /// + /// + Task RegisterAsync(RegisterInuput registerInuput); + + /// + /// 获取当前公司信息 + /// + /// + Task GetAsync(); + + /// + /// 根据Id获取公司信息 + /// + /// + Task GetByIdAsync(long companyId); + + /// + /// 更新公司信息 + /// + /// + /// + Task UpdateAsync(CompanyUpdateInput input); + + /// + /// 获取位置名称 + /// + /// + /// + /// + string GetAddress(decimal longitude, decimal latitude); + + /// + /// 修改公司停留标示 + /// + /// + /// + Task UpdatStopTagAsync(long stopTag); + + + /// + /// 一键派工是否显示工程名称 + /// + /// + Task UpdateIsOpenDispatchAsync(); + + /// + /// 调度角色是否有添 加工程名称的权限 + /// + /// + Task UpdateIsSchedulingAddProjectAsync(); + + + /// + /// 新增是否启用任务车型选项,默认为关 + /// + /// + Task UpdateIsOpenVehicleTypeAsync(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Construction/Dto/Input/ConstructionAddInput.cs b/src/Znyc.Dispatching.Application/Construction/Dto/Input/ConstructionAddInput.cs new file mode 100644 index 0000000..2df89bd --- /dev/null +++ b/src/Znyc.Dispatching.Application/Construction/Dto/Input/ConstructionAddInput.cs @@ -0,0 +1,32 @@ +using System.ComponentModel.DataAnnotations; + +namespace ZNYC.Recruitment.Service.Dictionary +{ + /// + /// 添加 + /// + public class ConstructionAddInput + { + /// + /// 施工单位 + /// + [Required(ErrorMessage = "请填写施工单位")] + public string ConstructionName { get; set; } + + /// + /// 联系人 + /// + public string ContactName { get; set; } + + /// + /// 联系电话 + /// + public string ContactPhone { get; set; } + + /// + /// 状态 + /// + public bool Status { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Construction/Dto/Input/ConstructionUpdateInput.cs b/src/Znyc.Dispatching.Application/Construction/Dto/Input/ConstructionUpdateInput.cs new file mode 100644 index 0000000..5462746 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Construction/Dto/Input/ConstructionUpdateInput.cs @@ -0,0 +1,14 @@ +namespace ZNYC.Recruitment.Service.Dictionary +{ + /// + /// 修改 + /// + public class ConstructionUpdateInput : ConstructionAddInput + { + /// + /// 主键Id + /// + public long Id { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Construction/Dto/Output/ConstructionOutput.cs b/src/Znyc.Dispatching.Application/Construction/Dto/Output/ConstructionOutput.cs new file mode 100644 index 0000000..305f659 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Construction/Dto/Output/ConstructionOutput.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class ConstructionBaiscList + { + public long Total { get; set; } + + public List ConstructionLetterOutputs { get; set; } + } + + + public class ConstructionLetterOutput + { + public string Char { get; set; } + + public List List { get; set; } + } + + public class ConstructionOutput + { + + /// + /// Id + /// + public long Id { get; set; } + + /// + /// 匹配索引列表,与车组人员共用一个列表,所以需增加UserId来进行匹配 + /// + public long UserId + { + get { return Id; } + set { Id = value; } + } + /// + /// 施工单位 + /// + public string ConstructionName { get; set; } + + /// + /// 联系人 + /// + public string ContactName { get; set; } + + /// + /// 联系电话 + /// + public string ContactPhone { get; set; } + + /// + /// 状态 + /// + public bool Status { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Construction/Services/ConstructionService.cs b/src/Znyc.Dispatching.Application/Construction/Services/ConstructionService.cs new file mode 100644 index 0000000..6594c9f --- /dev/null +++ b/src/Znyc.Dispatching.Application/Construction/Services/ConstructionService.cs @@ -0,0 +1,151 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Mapster; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Helpers; +using ZNYC.Recruitment.Service.Dictionary; + +namespace Znyc.Dispatching.Application.Services +{ + /// + /// 施工单位 + /// + [ApiDescriptionSettings(Name = "construction", Order = 259)] + public class ConstructionService : IConstructionService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _repository; + private readonly IRepository _projectRepository; + + private readonly IUserManager _userManager; + private string[] INDEX_STRINGS = {"A", "B", "C", "D", "E", "F", "G", "H", "I", + "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", + "W", "X", "Y", "Z", "#"}; + public ConstructionService( + IRepository repository, + ICacheService cacheService, + IUserManager userManager, + IRepository projectRepository) + { + _repository = repository; + _cacheService = cacheService; + _userManager = userManager; + _projectRepository = projectRepository; + } + + /// + /// InsertAsync + /// + /// + /// + [HttpPost] + [Route("api/v1/construction")] + public async Task InsertAsync(ConstructionAddInput constructionAddInput) + { + var result = false; + if (constructionAddInput.IsNotNull()) + { + var isRepeatConstructionName = await _repository.AnyAsync(x => x.ConstructionName == constructionAddInput.ConstructionName && x.CompanyId == _userManager.CompanyId); + if (isRepeatConstructionName) + { + throw Oops.Bah($"施工单位重名,请修改"); + } + var construction = constructionAddInput.Adapt(); + construction.CompanyId = _userManager.CompanyId; + long id = (await _repository.InsertNowAsync(construction)).Entity.Id; + if (id > 0) + { + result = true; + } + } + return result; + } + + + /// + /// UpdateAsync + /// + /// + /// + [HttpPut] + [Route("api/v1/construction")] + public async Task UpdateAsync(ConstructionUpdateInput constructionUpdateInput) + { + var result = false; + if (constructionUpdateInput.IsNotNull()) + { + var construction = await _repository.FindAsync(constructionUpdateInput.Id); + if (construction.IsNotNull()) + { + var isRepeatConstructionName = await _repository.AnyAsync(x => x.ConstructionName == constructionUpdateInput.ConstructionName && x.Id != constructionUpdateInput.Id && x.CompanyId == _userManager.CompanyId); + if (isRepeatConstructionName) + { + throw Oops.Bah($"施工单位重名,请修改"); + } + construction.ConstructionName = constructionUpdateInput.ConstructionName; + construction.ContactName = constructionUpdateInput.ContactName; + construction.ContactPhone = constructionUpdateInput.ContactPhone; + construction.Status = constructionUpdateInput.Status; + long id = (await _repository.UpdateNowAsync(construction)).Entity.Id; + if (id > 0) + { + //同步工程列表中施工单位名称 + var projects = _projectRepository.Where(x => x.ConstructionId == id).ToList(); + if (projects.Count > 0) + { + foreach (var project in projects) + { + project.ConstructionName = construction.ConstructionName; + await _projectRepository.UpdateNowAsync(project); + await _cacheService.RemoveProjectAsync(project.Id); + } + } + await _cacheService.RemoveProjectListAsync(_userManager.CompanyId); + + result = true; + } + } + } + return result; + } + + + + /// + /// ListAsync + /// + /// + [HttpGet] + [Route("api/v1/constructions/search")] + public async Task ListAsync(string key, int status) + { + var constructions = _repository.Where(x => x.CompanyId == _userManager.CompanyId) + .Where(key.IsNotEmptyOrNull(), x => x.ConstructionName.Contains(key)) + .Where(status > 0, x => x.Status) + .ToList().Adapt>(); + var constructionOutputs = new List(); + foreach (var INDEX_STRING in INDEX_STRINGS) + { + constructionOutputs.Add(new ConstructionLetterOutput() + { + Char = INDEX_STRING, + List = constructions.Where(x => StringHelper.GetStringFirstSpell(x.ConstructionName) == INDEX_STRING).ToList() + }); + }; + var data = new ConstructionBaiscList() + { + ConstructionLetterOutputs = constructionOutputs, + Total = constructions.Count + }; + return data; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Construction/Services/IConstructionService.cs b/src/Znyc.Dispatching.Application/Construction/Services/IConstructionService.cs new file mode 100644 index 0000000..780d092 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Construction/Services/IConstructionService.cs @@ -0,0 +1,31 @@ +using System.Threading.Tasks; +using ZNYC.Recruitment.Service.Dictionary; + +namespace Znyc.Dispatching.Application.Services +{ + public interface IConstructionService + { + + /// + /// InsertAsync + /// + /// + /// + public Task InsertAsync(ConstructionAddInput constructionAddInput); + + + /// + /// UpdateAsync + /// + /// + /// + public Task UpdateAsync(ConstructionUpdateInput constructionUpdateInput); + + + /// + /// + /// + /// + Task ListAsync(string key, int status); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Dictionary/Dto/Input/DictionaryAddInput.cs b/src/Znyc.Dispatching.Application/Dictionary/Dto/Input/DictionaryAddInput.cs new file mode 100644 index 0000000..10bbd5c --- /dev/null +++ b/src/Znyc.Dispatching.Application/Dictionary/Dto/Input/DictionaryAddInput.cs @@ -0,0 +1,38 @@ +namespace ZNYC.Recruitment.Service.Dictionary +{ + /// + /// 添加 + /// + public class DictionaryAddInput + { + /// + /// 字典父级 + /// + public int ParentId { get; set; } + + /// + /// 字典名称 + /// + public string Name { get; set; } + + /// + /// 字典编码 + /// + public string Code { get; set; } + + /// + /// 字典值 + /// + public string Value { get; set; } + + /// + /// 描述 + /// + public string Description { get; set; } + + /// + /// 启用 + /// + public bool IsEnable { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Dictionary/Dto/Input/DictionaryUpdateInput.cs b/src/Znyc.Dispatching.Application/Dictionary/Dto/Input/DictionaryUpdateInput.cs new file mode 100644 index 0000000..931fd9d --- /dev/null +++ b/src/Znyc.Dispatching.Application/Dictionary/Dto/Input/DictionaryUpdateInput.cs @@ -0,0 +1,18 @@ +namespace ZNYC.Recruitment.Service.Dictionary +{ + /// + /// 修改 + /// + public class DictionaryUpdateInput : DictionaryAddInput + { + /// + /// 主键Id + /// + public int Id { get; set; } + + /// + /// 版本 + /// + public int Version { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Dictionary/Dto/Output/DictionaryOutput.cs b/src/Znyc.Dispatching.Application/Dictionary/Dto/Output/DictionaryOutput.cs new file mode 100644 index 0000000..ca9cf48 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Dictionary/Dto/Output/DictionaryOutput.cs @@ -0,0 +1,30 @@ +namespace Znyc.Dispatching.Application +{ + public class DictionaryOutput + { + /// + /// 主键Id + /// + public long Id { get; set; } + + /// + /// 字典编码 + /// + public string Code { get; set; } + + /// + /// 字典值 + /// + public string Value { get; set; } + + /// + /// 字典名称 + /// + public string Name { get; set; } + + /// + /// 排序 + /// + public int Sort { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Dictionary/Services/DictionaryService.cs b/src/Znyc.Dispatching.Application/Dictionary/Services/DictionaryService.cs new file mode 100644 index 0000000..8301aa5 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Dictionary/Services/DictionaryService.cs @@ -0,0 +1,52 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Application.Services +{ + /// + /// 字典服务 + /// + [ApiDescriptionSettings(Name = "dictionary", Order = 200)] + public class DictionaryService : IDictionaryService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _repository; + + public DictionaryService( + IRepository repository, + ICacheService cacheService) + { + _repository = repository; + _cacheService = cacheService; + } + + /// + /// 根据Id获取字典 + /// + /// + /// + [HttpGet] + public async Task GetAsync(long id) + { + List dictionarys = await _cacheService.GetDictionaryListAsync(); + return dictionarys.Find(x => x.Id == id); + } + + /// + /// 根据code获取字典 + /// + /// + /// + [HttpGet] + public async Task> ListAsync(string code) + { + List dictionarys = await _cacheService.GetDictionaryListAsync(); + return dictionarys.FindAll(x => x.Code == code); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Dictionary/Services/IDictionaryService.cs b/src/Znyc.Dispatching.Application/Dictionary/Services/IDictionaryService.cs new file mode 100644 index 0000000..5844d34 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Dictionary/Services/IDictionaryService.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application.Services +{ + public interface IDictionaryService + { + /// + /// 根据Id获取字典 + /// + /// + /// + Task GetAsync(long id); + + /// + /// 根据code获取字典 + /// + /// + /// + Task> ListAsync(string code); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Document/Dto/Output/BucketTokenOutput.cs b/src/Znyc.Dispatching.Application/Document/Dto/Output/BucketTokenOutput.cs new file mode 100644 index 0000000..a7b7a08 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Document/Dto/Output/BucketTokenOutput.cs @@ -0,0 +1,24 @@ +namespace Znyc.Dispatching.Application +{ + public class BucketTokenOutput + { + public Credentials Credentials { get; set; } + + public string Expiration { get; set; } + + public int ExpiredTime { get; set; } + + public string RequestId { get; set; } + + public int StartTime { get; set; } + } + + public class Credentials + { + public string TmpSecretId { get; set; } + + public string TmpSecretKey { get; set; } + + public string Token { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Document/Services/DocumentService.cs b/src/Znyc.Dispatching.Application/Document/Services/DocumentService.cs new file mode 100644 index 0000000..e2f5917 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Document/Services/DocumentService.cs @@ -0,0 +1,58 @@ +using COSSTS; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using Znyc.Dispatching.Core; + +namespace Znyc.Dispatching.Application +{ + /// + /// Cos服务 + /// + [ApiDescriptionSettings(Name = "document", Order = 150, IgnoreApi = false)] + public class DocumentService : IDocumentService, IDynamicApiController, ITransient + { + private readonly UploadInfoOptions _uploadInfoOptions; + + public DocumentService( + IOptions options + ) + { + _uploadInfoOptions = options.Value; + } + + /// + /// 获取COS_Token + /// + /// + [HttpGet] + [AllowAnonymous] + [Route("api/v1/costoken")] + public BucketTokenOutput GetBucketTokenAsync() + { + Dictionary values = new Dictionary + { + ["allowActions"] = _uploadInfoOptions.allowActions, + ["bucket"] = _uploadInfoOptions.bucket, + ["region"] = _uploadInfoOptions.region, + ["allowPrefix"] = _uploadInfoOptions.allowPrefix, + ["allowActions"] = _uploadInfoOptions.allowActions, + ["durationSeconds"] = _uploadInfoOptions.durationSeconds, + ["secretId"] = _uploadInfoOptions.secretId, + ["secretKey"] = _uploadInfoOptions.secretKey + }; + Dictionary credential = STSClient.genCredential(values); + foreach (KeyValuePair kvp in credential) + { + Console.WriteLine("{0} = {1}", kvp.Key, kvp.Value); + } + + return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(credential)); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Document/Services/IDocumentService.cs b/src/Znyc.Dispatching.Application/Document/Services/IDocumentService.cs new file mode 100644 index 0000000..6be73ad --- /dev/null +++ b/src/Znyc.Dispatching.Application/Document/Services/IDocumentService.cs @@ -0,0 +1,11 @@ +namespace Znyc.Dispatching.Application +{ + public interface IDocumentService + { + /// + /// 获取COS_Token + /// + /// + BucketTokenOutput GetBucketTokenAsync(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Employee/Dto/Input/EmployeeAddInput.cs b/src/Znyc.Dispatching.Application/Employee/Dto/Input/EmployeeAddInput.cs new file mode 100644 index 0000000..34f0368 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Employee/Dto/Input/EmployeeAddInput.cs @@ -0,0 +1,33 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + public class EmployeeAddInput + { + /// + /// 员工名 + /// + [Required(ErrorMessage = "员工名不能为空!")] + public string EmployeeName { get; set; } + + /// + /// 手机号 + /// + [Required(ErrorMessage = "请输入手机号")] + [MaxLength(11, ErrorMessage = "手机号不能超过11位")] + [RegularExpression("^[1][3,4,5,6,7,8,9][0-9]{9}$", ErrorMessage = "请输入正确的手机号码")] + public string EmployeePhone { get; set; } + + /// + /// 角色 + /// + public int RoleId { get; set; } + + /// + /// 角色名称 + /// + [Required(ErrorMessage = "角色名称不能为空!")] + [MaxLength(20, ErrorMessage = "角色名称不得超过8个字")] + public string RoleName { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Employee/Dto/Input/EmployeeUpdateInput.cs b/src/Znyc.Dispatching.Application/Employee/Dto/Input/EmployeeUpdateInput.cs new file mode 100644 index 0000000..2080557 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Employee/Dto/Input/EmployeeUpdateInput.cs @@ -0,0 +1,17 @@ +namespace Znyc.Dispatching.Application +{ + public class EmployeeUpdateInput : EmployeeAddInput + { + public long Id { get; set; } + + /// + /// 状态 + /// + public int Status { get; set; } + + /// + /// 员工头像 + /// + public string AvatarUrl { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Employee/Dto/OutPut/EmployeeListOutput.cs b/src/Znyc.Dispatching.Application/Employee/Dto/OutPut/EmployeeListOutput.cs new file mode 100644 index 0000000..632d5dc --- /dev/null +++ b/src/Znyc.Dispatching.Application/Employee/Dto/OutPut/EmployeeListOutput.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + public class EmployeeListOutput + { + /// + /// + public long Id { get; set; } + + /// + /// 用户Id + /// + public long UserId { get; set; } + + + /// + /// + /// + public int RoleId { get; set; } + + /// + /// + /// + public string RoleName { get; set; } + + /// + /// 员工名 + /// + public string EmployeeName { get; set; } + + /// + /// 手机号 + /// + [MaxLength(11)] + public string EmployeePhone { get; set; } + + + public int Status { get; set; } + + } + + public class EmployeeListOutputs + { + public string Char { get; set; } + + public List List { get; set; } + + } + + public class EmployeeListPage + { + public List EmployeeList { get; set; } + + public long Total { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Employee/Dto/OutPut/EmployeeOutput.cs b/src/Znyc.Dispatching.Application/Employee/Dto/OutPut/EmployeeOutput.cs new file mode 100644 index 0000000..2e2ddf6 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Employee/Dto/OutPut/EmployeeOutput.cs @@ -0,0 +1,52 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + public class EmployeeOutput + { + /// + /// + public long Id { get; set; } + + /// + /// 用户Id + /// + public long UserId { get; set; } + + /// + /// 公司Id + /// + public long CompanyId { get; set; } + + /// + /// 员工名 + /// + public string EmployeeName { get; set; } + + /// + /// 手机号 + /// + [MaxLength(11)] + public string EmployeePhone { get; set; } + + /// + /// 角色 + /// + public long RoleId { get; set; } + + /// + /// 角色名称 + /// + public string RoleName { get; set; } + + /// + /// 状态 + /// + public int Status { get; set; } + + /// + /// 员工头像 + /// + public string AvatarUrl { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Employee/Dto/OutPut/NoticeOutput.cs b/src/Znyc.Dispatching.Application/Employee/Dto/OutPut/NoticeOutput.cs new file mode 100644 index 0000000..9e39a27 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Employee/Dto/OutPut/NoticeOutput.cs @@ -0,0 +1,7 @@ +namespace Znyc.Dispatching.Application +{ + public class NoticeOutput + { + public string OpenId { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Employee/Services/EmployeeService.cs b/src/Znyc.Dispatching.Application/Employee/Services/EmployeeService.cs new file mode 100644 index 0000000..c756bdf --- /dev/null +++ b/src/Znyc.Dispatching.Application/Employee/Services/EmployeeService.cs @@ -0,0 +1,305 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Mapster; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Common.Extensions; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Helpers; + +namespace Znyc.Dispatching.Application +{ + /// + /// 员工服务 + /// + [ApiDescriptionSettings(Name = "employee", Order = 20)] + public class EmployeeService : IEmployeeService, IDynamicApiController, ITransient + { + private string[] INDEX_STRINGS = {"A", "B", "C", "D", "E", "F", "G", "H", "I", + "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", + "W", "X", "Y", "Z", "#"}; + + private string[] ROLEINDEX_STRINGS = { "C", "D", "J", "G", "W", "Y", "X", "#" }; + + + private readonly ICacheService _cacheService; + private readonly IRepository _repository; + private readonly IRepository _userRepository; + private readonly IRepository _userRoleRepository; + private readonly IRepository _companyRepository; + private readonly IUserManager _userManager; + private readonly IRepository _vehiclePersonRepository; + private readonly IRepository _projectPersonRepository; + + + public EmployeeService( + IRepository repository, + IRepository userRepository, + IRepository companyRepository, + IUserManager userManager, + ICacheService cacheService, + IRepository userRoleRepository, + IOptions smsProviderOptions, + IRepository vehiclePersonRepository, + IRepository projectPersonRepository + ) + { + _repository = repository; + _userRepository = userRepository; + _companyRepository = companyRepository; + _userManager = userManager; + _cacheService = cacheService; + _userRoleRepository = userRoleRepository; + _vehiclePersonRepository = vehiclePersonRepository; + _projectPersonRepository = projectPersonRepository; + } + + /// + /// 员工信息 + /// + /// + /// + /// + /// 0全部,停用-1,正常1 + /// + /// + /// + [HttpGet] + [Route("api/v1/employees/search")] + public async Task PageAsync([Required] int currentPage, [Required] int pageSize, [FromQuery] int status, [Required] int roleId, [FromQuery] string orderby, [FromQuery] string key = "") + { + + var employees = (await _cacheService.GetEmployeeListAsync(_userManager.CompanyId)) + .WhereIf(status != 0, x => x.Status == status) + .WhereIf(roleId > 0, x => x.RoleId == roleId) + .WhereIf(new long[] { (long)RoleStatusEnum.Scheduling, (long)RoleStatusEnum.CarCaptain }.Contains(_userManager.RoleId), + x => new long[] { (long)RoleStatusEnum.CrewMembers, (long)RoleStatusEnum.Outside, + (long)RoleStatusEnum.PartTimeSalesman,(long)RoleStatusEnum.Salesman }.Contains(x.RoleId)) + .WhereIf(key.IsNotEmptyOrNull(), x => x.EmployeeName.Contains(key) || x.EmployeePhone.Contains(key)) + .Adapt>(); + var employeeOutputs = new List(); + + if (orderby == "role") + { + employees = employees.OrderBy(x => x.RoleName).ToList(); + foreach (var INDEX_STRING in ROLEINDEX_STRINGS) + { + employeeOutputs.Add(new EmployeeListOutputs() + { + Char = INDEX_STRING, + List = employees.Where(x => StringHelper.GetStringFirstSpell(x.RoleName) == INDEX_STRING).ToList() + }); + }; + } + else + { + employees = employees.OrderBy(x => x.EmployeeName).ToList(); + + foreach (var INDEX_STRING in INDEX_STRINGS) + { + employeeOutputs.Add(new EmployeeListOutputs() + { + Char = INDEX_STRING, + List = employees.Where(x => StringHelper.GetStringFirstSpell(x.EmployeeName) == INDEX_STRING).ToList() + }); + }; + } + var data = new EmployeeListPage() + { + EmployeeList = employeeOutputs, + Total = employees.Count + }; + return data; + } + + /// + /// 根据id获取员工资料 + /// + /// + [HttpGet] + [Route("api/v1/employee/{id}")] + public async Task GetByIdAsync(long id) + { + return await _cacheService.GetEmployeeAsync(id); + } + + /// + /// 添加员工信息 + /// + /// + /// + [HttpPost] + [UnitOfWork] + [NonAction] + //[Route("api/v1/employee")] + public async Task AddAsync(EmployeeAddInput employeeAdd) + { + var user = await _userRepository.Where(x => x.Phone == employeeAdd.EmployeePhone).FirstOrDefaultAsync(); + if (user.IsNotNull()) + { + return user.Id; + } + + var company = await _companyRepository.FindOrDefaultAsync(_userManager.CompanyId); + if (company.IsNotNull()) + { + //用户 + var userEntity = await _userRepository.InsertNowAsync(new User + { + OpenId = "", + UserName = employeeAdd.EmployeeName, + AvatarUrl = CommonConst.DEFAULT_AVATARURL_ALL, + Phone = employeeAdd.EmployeePhone, + Status = CommonStatusEnum.ENABLE + }); + //员工 + var employee = await _repository.InsertNowAsync(new Employee + { + UserId = userEntity.Entity.Id, + AvatarUrl = CommonConst.DEFAULT_AVATARURL, + EmployeeName = employeeAdd.EmployeeName, + EmployeePhone = employeeAdd.EmployeePhone, + CompanyId = company.Id, + RoleId = employeeAdd.RoleId, + RoleName = employeeAdd.RoleName, + IsDefault = true, + Status = (int)CommonStatusEnum.ENABLE + }); + //用户角色 + await _userRoleRepository.InsertNowAsync(new UserRole + { + UserId = userEntity.Entity.Id, + RoleId = employeeAdd.RoleId, + }); + //清除员工列表Cache + await _cacheService.RemoveEmployeeListAsync(_userManager.CompanyId); + return employee.Entity.UserId; + } + else + { + return 0; + } + } + + /// + /// 编辑员工信息 + /// + /// + [HttpPut] + [UnitOfWork] + [Route("api/v1/employee")] + public async Task UpdateAsync(EmployeeUpdateInput input) + { + var employee = await _repository.FindOrDefaultAsync(input.Id); + //权限变动,清除对应缓存 + if (!employee.RoleId.Equals(input.RoleId)) + { + await _cacheService.RemoveTokenAsync(employee.UserId); + } + employee = input.Adapt(employee); + employee.AvatarUrl = CommonConst.Prefix_AvataUrl + employee.AvatarUrl[(employee.AvatarUrl.LastIndexOf("/") + 1)..]; + var result = await _repository.UpdateNowAsync(employee); + if (result.IsNull()) + { + throw Oops.Oh("更新员工信息失败"); + } + //同步更新user + var user = await _userRepository.FirstOrDefaultAsync(x => x.Id == employee.UserId); + if (user.IsNotNull()) + { + user.UserName = input.EmployeeName; + user.Phone = input.EmployeePhone; + user.AvatarUrl = employee.AvatarUrl; + await _userRepository.UpdateNowAsync(user); + await _cacheService.RemoveUserAsync(user.Id); + } + + //更新当前用户下所有角色姓名 + var employees = await _repository.Where(x => x.UserId == user.Id).ToListAsync(); + foreach (var employee2 in employees) + { + if (employee.IsNotNull()) + { + employee.EmployeePhone = input.EmployeePhone; + employee.EmployeeName = input.EmployeeName; + employee.AvatarUrl = CommonConst.Prefix_AvataUrl + input.AvatarUrl[(input.AvatarUrl.LastIndexOf("/") + 1)..]; + await _repository.UpdateNowAsync(employee2); + await _cacheService.RemoveEmployeeAsync(employee2.Id); + await _cacheService.RemoveEmployeeListAsync(employee2.CompanyId); + } + } + + + //清除员工Cache + await _cacheService.RemoveEmployeeAsync(employee.Id); + //清除用户Cache + await _cacheService.RemoveUserAsync(employee.UserId); + //清除员工列表Cache + await _cacheService.RemoveEmployeeListAsync(_userManager.CompanyId); + //同步车组人员表 + var vehiclePersons = await _vehiclePersonRepository.Where(x => x.IsDeleted == false && x.UserId == user.Id).ToListAsync(); + foreach (var item in vehiclePersons) + { + //解除车组人员关联 + if (input.Status == (int)CommonStatusEnum.DISABLE) + { + item.IsDeleted = true; + } + item.UserName = input.EmployeeName; + item.UserPhone = input.EmployeePhone; + await _vehiclePersonRepository.UpdateNowAsync(item); + //删除车组人员Cache + await _cacheService.RemoveVehiclePersonAsync(item.VehicleId); + } + //同步工程联系人表 + var projectPersons = await _projectPersonRepository.Where(x => x.IsDeleted == false && x.ProjectPersonId == user.Id).ToListAsync(); + foreach (var item in projectPersons) + { + item.ProjectPersonName = input.EmployeeName; + item.ProjectPersonPhone = input.EmployeePhone; + await _projectPersonRepository.UpdateNowAsync(item); + //清除工程信息Cache + await _cacheService.RemoveProjectAsync(item.ProjectId); + //清除工程列表信息Cache + await _cacheService.RemoveProjectListAsync(_userManager.CompanyId); + } + //同步用户角色表 + //var userRole = await _userRoleRepository.FirstOrDefaultAsync(x => x.UserId == employee.UserId); + //userRole.RoleId = employee.RoleId; + //await _userRoleRepository.UpdateNowAsync(userRole); + + } + + + /// + /// 软删除员工信息 + /// + /// + /// + [HttpDelete] + [Route("api/v1/employee")] + + public async Task DeleteByIdAsync(long id) + { + Employee employee = await _repository + .FirstOrDefaultAsync(x => x.Id == id && x.CompanyId == _userManager.CompanyId); + employee.IsDeleted = true; + await _repository.UpdateNowAsync(employee); + await _cacheService.RemoveCacheByUserIdAsync(employee.UserId); + await _cacheService.RemoveEmployeeAsync(employee.Id); + await _cacheService.RemoveEmployeeListAsync(_userManager.CompanyId); + await _cacheService.RemoveUserAsync(employee.UserId); + } + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Employee/Services/IEmployeeService.cs b/src/Znyc.Dispatching.Application/Employee/Services/IEmployeeService.cs new file mode 100644 index 0000000..e4df847 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Employee/Services/IEmployeeService.cs @@ -0,0 +1,50 @@ +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IEmployeeService + { + /// + /// 员工信息 + /// + /// + /// + /// + /// + /// + /// + /// + Task PageAsync(int currentPage, int pageSize, int status, int roleId, string key, string orderby); + + + /// + /// 根据id获取员工资料 + /// + /// + Task GetByIdAsync(long id); + + /// + /// 添加员工信息 + /// + /// + /// + Task AddAsync(EmployeeAddInput input); + + /// + /// 编辑员工信息 + /// + /// + Task UpdateAsync(EmployeeUpdateInput input); + + + /// + /// 软删除员工信息 + /// + /// + /// + Task DeleteByIdAsync(long id); + + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Job/Dto/Input/JobInput.cs b/src/Znyc.Dispatching.Application/Job/Dto/Input/JobInput.cs new file mode 100644 index 0000000..910ada6 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Job/Dto/Input/JobInput.cs @@ -0,0 +1,83 @@ +using Furion.DataValidation; +using Furion.TaskScheduler; +using System.ComponentModel.DataAnnotations; +using Znyc.Dispatching.Core; + +namespace Dilon.Core.Service +{ + /// + /// 任务调度参数 + /// + public class JobInput : PageInputBase + { + /// + /// 任务名称 + /// + public string JobName { get; set; } + + /// + /// 执行间隔时间(单位秒) + /// + /// 5 + public int Interval { get; set; } + + /// + /// Cron表达式 + /// + public string Cron { get; set; } + + /// + /// 定时器类型 + /// + public SpareTimeTypes TimerType { get; set; } + + /// + /// 执行次数 + /// + public int? RunNumber { get; set; } + + /// + /// 请求url + /// + public string RequestUrl { get; set; } + + /// + /// 请求参数(Post,Put请求用) + /// + public string RequestParameters { get; set; } + + /// + /// Headers(可以包含如:Authorization授权认证) + /// 格式:{"Authorization":"userpassword.."} + /// + public string Headers { get; set; } + + /// + /// 请求类型 + /// + public RequestTypeEnum RequestType { get; set; } + + /// + /// 备注 + /// + public string Remark { get; set; } + } + + public class DeleteJobInput : JobInput + { + /// + /// 任务Id + /// + [Required(ErrorMessage = "任务Id不能为空")] + [DataValidation(ValidationTypes.Numeric)] + public long Id { get; set; } + } + + public class UpdateJobInput : DeleteJobInput + { + } + + public class QueryJobInput : DeleteJobInput + { + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Job/Dto/Output/JobOutput.cs b/src/Znyc.Dispatching.Application/Job/Dto/Output/JobOutput.cs new file mode 100644 index 0000000..c83a32a --- /dev/null +++ b/src/Znyc.Dispatching.Application/Job/Dto/Output/JobOutput.cs @@ -0,0 +1,78 @@ +using Furion.TaskScheduler; +using Znyc.Dispatching.Core; + +namespace Dilon.Core.Service +{ + /// + /// 任务信息---任务详情 + /// + public class JobOutput + { + /// + /// Id + /// + public long Id { get; set; } + + /// + /// 任务名称 + /// + public string JobName { get; set; } + + /// + /// 执行间隔时间(单位秒) + /// + public int Interval { get; set; } + + /// + /// Cron表达式 + /// + public string Cron { get; set; } + + /// + /// 定时器类型 + /// + public SpareTimeTypes TimerType { get; set; } + + /// + /// 执行次数 + /// + public long? RunNumber { get; set; } + + /// + /// 请求url + /// + public string RequestUrl { get; set; } + + /// + /// 请求参数(Post,Put请求用) + /// + public string RequestParameters { get; set; } + + /// + /// Headers(可以包含如:Authorization授权认证) + /// 格式:{"Authorization":"userpassword.."} + /// + public string Headers { get; set; } + + /// + /// 请求类型 + /// + /// 2 + public RequestTypeEnum RequestType { get; set; } + + /// + /// 备注 + /// + public string Remark { get; set; } + + /// + /// 定时器状态 + /// + public SpareTimeStatus TimerStatus { get; set; } = SpareTimeStatus.Stopped; + + /// + /// 异常信息 + /// + public string Exception { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Job/IJobService.cs b/src/Znyc.Dispatching.Application/Job/IJobService.cs new file mode 100644 index 0000000..225b82b --- /dev/null +++ b/src/Znyc.Dispatching.Application/Job/IJobService.cs @@ -0,0 +1,10 @@ +using System.Threading.Tasks; + +namespace Dilon.Core.Service +{ + public interface IJobService + { + + Task SyncOrderStatusAsync(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Job/JobService.cs b/src/Znyc.Dispatching.Application/Job/JobService.cs new file mode 100644 index 0000000..bc45e24 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Job/JobService.cs @@ -0,0 +1,277 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Newtonsoft.Json; +using Senparc.Weixin.MP.AdvancedAPIs; +using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage; +using System; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Application; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Helpers; +using Znyc.Dispatching.MongoDb.Repository.Repositorys; +using Znyc.Dispatching.WeChat.Core.CommonService.TemplateMessage; + +namespace Dilon.Core.Service +{ + /// + /// 任务调度服务 + /// + [ApiDescriptionSettings(Name = "job", Order = 40)] + public class JobService : IJobService, IDynamicApiController, IScoped + { + private readonly IRepository _roleRepository; + private readonly IVehicleService _vehicleService; + private readonly IRepository _menuRepository; + private readonly IRepository _roleMenuRepository; + private readonly IRepository _orderRepository; + private readonly IGpsRealTimeRepository _gpsRealTimeRepository; + private readonly ICacheService _cacheService; + private readonly IRepository _employeeRepository; + private readonly IRepository _orderVehicleRepository; + private readonly IRepository _wxUserRelationRepository; + private readonly WeixinSettingOptions _weixinSettingOptions; + private readonly IRepository _yardRepository; + private readonly IRepository _companyRepository; + public JobService( + IRepository roleRepository, + IVehicleService vehicleService, + ICacheService cacheService, + IRepository menuRepository, + IRepository orderRepository, + IRepository roleMenuRepository, + IGpsRealTimeRepository gpsRealTimeRepository, + IRepository employeeRepository, + IRepository orderVehicleRepository, + IRepository wxUserRelationRepository, + IOptions weixinSettingOptions, + IRepository yardRepository, + IRepository companyRepository) + { + _roleRepository = roleRepository; + _vehicleService = vehicleService; + _menuRepository = menuRepository; + _cacheService = cacheService; + _orderRepository = orderRepository; + _roleMenuRepository = roleMenuRepository; + _gpsRealTimeRepository = gpsRealTimeRepository; + _employeeRepository = employeeRepository; + _orderVehicleRepository = orderVehicleRepository; + _wxUserRelationRepository = wxUserRelationRepository; + _weixinSettingOptions = weixinSettingOptions.Value; + _yardRepository = yardRepository; + _companyRepository = companyRepository; + } + + #region Order + + [HttpGet] + [AllowAnonymous] + public async Task SyncOrderStatusAsync() + { + var orders = _orderRepository.Where(x => x.IsDeleted == false && new int[] { (int)OrderStatus.Receive, (int)OrderStatus.Travel, (int)OrderStatus.Appear, (int)OrderStatus.Sign, (int)OrderStatus.Leave }.Contains(x.Status)).ToList(); + var vehicleGpss = await _gpsRealTimeRepository.GetGpsRealTimeListByVehicleId(orders.Select(x => x.VehicleId).ToList()); + var arriveOrders = orders.Where(x => x.Status == (int)OrderStatus.Receive && x.Latitude > 0 && x.Longitude > 0).ToList(); + + foreach (var arriveOrder in arriveOrders) + { + var vehicleGps = vehicleGpss.Where(x => x.VehicleId == arriveOrder.VehicleId).FirstOrDefault(); + if (vehicleGps.IsNotNull()) + { + //已出发 + var vehicleTravelGps = await _cacheService.GetVehicleGpsAsync(arriveOrder.Id); + if (vehicleTravelGps.IsNotNull()) + { + var distance = MapHelper.GetDistance((double)vehicleGps.Latitude, (double)vehicleGps.Longitude, (double)vehicleTravelGps.Latitude, (double)vehicleTravelGps.Longitude); + if (distance > 3000) + { + arriveOrder.Status = (int)OrderStatus.Travel; + arriveOrder.TravelDate = DateTime.Now; + var orderId = (await _orderRepository.UpdateNowAsync(arriveOrder)).Entity.Id; + if (orderId > 0) + { + var orderContent = arriveOrder.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark(arriveOrder.OrderContent.Substring(0, 45)) + "..." : HtmlHelper.ReplaceHtmlMark(arriveOrder.OrderContent) + "..."; + + //管理员 + var adminUserIds = await _employeeRepository.DetachedEntities.Where(x => x.CompanyId == arriveOrder.CompanyId && x.RoleId == (int)RoleStatusEnum.Administrator && x.Status == 1 && !x.IsDeleted).Select(x => x.UserId).ToListAsync(); + //派单人 + adminUserIds.Add(arriveOrder.AssignUserId); + //获取订单所有车组人员信息 + var orderVehicles = await _orderVehicleRepository.DetachedEntities.Where(x => x.OrderId == arriveOrder.Id).ToListAsync(); + var orderVehicleDriverName = orderVehicles.FirstOrDefault(x => x.IsDriver).UserName; + var orderVehicleCrewsName = string.Join(",", orderVehicles.Where(x => !x.IsDriver).Select(x => x.UserName).ToList()); + foreach (var adminUserId in adminUserIds) + { + var wxAdminUser = _wxUserRelationRepository.Where(x => x.UserId == adminUserId).FirstOrDefault(); + if (wxAdminUser.IsNotNull() && wxAdminUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("已出发提醒", arriveOrder.ProjectName, "出车任务", orderContent, arriveOrder.ArriveDate.ToString("yyyy -MM-dd HH:mm:ss"), $"[{arriveOrder.VehicleCode}]号车,{orderVehicleDriverName},{orderVehicleCrewsName}已出发"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={arriveOrder.Id}&isDriver=false&type=2"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxAdminUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"已出发提醒{JsonConvert.SerializeObject(result)}"); + } + } + } + await _cacheService.RemoveVehicleGpsAsync(arriveOrder.Id); + } + } + + + } + } + + //已到达 + var appearOrders = orders.Where(x => x.Status == (int)OrderStatus.Travel && x.Latitude > 0 && x.Longitude > 0).ToList(); + foreach (var appearOrder in appearOrders) + { + var vehicleGps = vehicleGpss.Where(x => x.VehicleId == appearOrder.VehicleId).FirstOrDefault(); + if (vehicleGps.IsNotNull()) + { + var distance = MapHelper.GetDistance((double)vehicleGps.Latitude, (double)vehicleGps.Longitude, (double)appearOrder.Latitude, (double)appearOrder.Longitude); + if (distance < 200) + { + appearOrder.Status = (int)OrderStatus.Appear; + appearOrder.AppearDate = DateTime.Now; + var orderId = (await _orderRepository.UpdateNowAsync(appearOrder)).Entity.Id; + if (orderId > 0) + { + var orderContent = appearOrder.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark(appearOrder.OrderContent.Substring(0, 45)) + "..." : HtmlHelper.ReplaceHtmlMark(appearOrder.OrderContent) + "..."; + + //管理员 + var adminUserIds = await _employeeRepository.DetachedEntities.Where(x => x.CompanyId == appearOrder.CompanyId && x.RoleId == (int)RoleStatusEnum.Administrator && x.Status == 1 && !x.IsDeleted).Select(x => x.UserId).ToListAsync(); + //派单人 + adminUserIds.Add(appearOrder.AssignUserId); + //获取订单所有车组人员信息 + var orderVehicles = await _orderVehicleRepository.DetachedEntities.Where(x => x.OrderId == appearOrder.Id).ToListAsync(); + var orderVehicleDriverName = orderVehicles.FirstOrDefault(x => x.IsDriver).UserName; + var orderVehicleCrewsName = string.Join(",", orderVehicles.Where(x => !x.IsDriver).Select(x => x.UserName).ToList()); + foreach (var adminUserId in adminUserIds) + { + var wxAdminUser = _wxUserRelationRepository.Where(x => x.UserId == adminUserId).FirstOrDefault(); + if (wxAdminUser.IsNotNull() && wxAdminUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("已到达提醒", appearOrder.ProjectName, "出车任务", orderContent, appearOrder.ArriveDate.ToString("yyyy -MM-dd HH:mm:ss"), $"[{appearOrder.VehicleCode}]号车,{orderVehicleDriverName},{orderVehicleCrewsName}已到达施工地点"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={appearOrder.Id}&isDriver=false&type=2"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxAdminUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"已到达提醒{JsonConvert.SerializeObject(result)}"); + } + } + } + } + } + } + + //已离开 + var signeOrders = orders.Where(x => x.Status == (int)OrderStatus.Sign && x.Latitude > 0 && x.Longitude > 0).ToList(); + foreach (var signeOrder in signeOrders) + { + var vehicleGps = vehicleGpss.Where(x => x.VehicleId == signeOrder.VehicleId).FirstOrDefault(); + if (vehicleGps.IsNotNull()) + { + var distance = MapHelper.GetDistance((double)vehicleGps.Latitude, (double)vehicleGps.Longitude, (double)signeOrder.Latitude, (double)signeOrder.Longitude); + if (distance > 200) + { + signeOrder.Status = (int)OrderStatus.Leave; + signeOrder.LeaveDate = DateTime.Now; + var orderId = (await _orderRepository.UpdateNowAsync(signeOrder)).Entity.Id; + if (orderId > 0) + { + var orderContent = signeOrder.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark(signeOrder.OrderContent.Substring(0, 45)) + "..." : HtmlHelper.ReplaceHtmlMark(signeOrder.OrderContent) + "..."; + + //管理员 + var adminUserIds = await _employeeRepository.DetachedEntities.Where(x => x.CompanyId == signeOrder.CompanyId && x.RoleId == (int)RoleStatusEnum.Administrator && x.Status == 1 && !x.IsDeleted).Select(x => x.UserId).ToListAsync(); + //派单人 + adminUserIds.Add(signeOrder.AssignUserId); + //获取订单所有车组人员信息 + var orderVehicles = await _orderVehicleRepository.DetachedEntities.Where(x => x.OrderId == signeOrder.Id).ToListAsync(); + var orderVehicleDriverName = orderVehicles.FirstOrDefault(x => x.IsDriver).UserName; + var orderVehicleCrewsName = string.Join(",", orderVehicles.Where(x => !x.IsDriver).Select(x => x.UserName).ToList()); + foreach (var adminUserId in adminUserIds) + { + var wxAdminUser = _wxUserRelationRepository.Where(x => x.UserId == adminUserId).FirstOrDefault(); + if (wxAdminUser.IsNotNull() && wxAdminUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("完工返回提醒", signeOrder.ProjectName, "出车任务", orderContent, signeOrder.ArriveDate.ToString("yyyy -MM-dd HH:mm:ss"), $"[{signeOrder.VehicleCode}]号车,{orderVehicleDriverName},{orderVehicleCrewsName}已完工返回"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={signeOrder.Id}&isDriver=false&type=2"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxAdminUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"已到达提醒{JsonConvert.SerializeObject(result)}"); + } + } + } + } + } + } + + + //已到家 + var homeOrders = orders.Where(x => x.Status == (int)OrderStatus.Leave && x.Latitude > 0 && x.Longitude > 0).ToList(); + foreach (var homeOrder in homeOrders) + { + var vehicleGps = vehicleGpss.Where(x => x.VehicleId == homeOrder.VehicleId).FirstOrDefault(); + + //查询所有车场位置 + var yards = await _yardRepository.DetachedEntities.Where(x => x.CompanyId == homeOrder.CompanyId).ToListAsync(); + foreach (var yard in yards) + { + if (vehicleGps.IsNotNull()) + { + var distance = MapHelper.GetDistance((double)vehicleGps.Latitude, (double)vehicleGps.Longitude, (double)yard.Latitude, (double)yard.Longitude); + if (distance < 200) + { + + homeOrder.Status = (int)OrderStatus.ArriveHome; + homeOrder.ArriveHomeDate = DateTime.Now; + var orderId = (await _orderRepository.UpdateNowAsync(homeOrder)).Entity.Id; + if (orderId > 0) + { + + var orderContent = homeOrder.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark(homeOrder.OrderContent.Substring(0, 45)) + "..." : HtmlHelper.ReplaceHtmlMark(homeOrder.OrderContent) + "..."; + //管理员 + var adminUserIds = await _employeeRepository.DetachedEntities.Where(x => x.CompanyId == homeOrder.CompanyId && x.RoleId == (int)RoleStatusEnum.Administrator && x.Status == 1 && !x.IsDeleted).Select(x => x.UserId).ToListAsync(); + //派单人 + adminUserIds.Add(homeOrder.AssignUserId); + //获取订单所有车组人员信息 + var orderVehicles = await _orderVehicleRepository.DetachedEntities.Where(x => x.OrderId == homeOrder.Id).ToListAsync(); + var orderVehicleDriverName = orderVehicles.FirstOrDefault(x => x.IsDriver).UserName; + var orderVehicleCrewsName = string.Join(",", orderVehicles.Where(x => !x.IsDriver).Select(x => x.UserName).ToList()); + foreach (var adminUserId in adminUserIds) + { + var wxAdminUser = _wxUserRelationRepository.Where(x => x.UserId == adminUserId).FirstOrDefault(); + if (wxAdminUser.IsNotNull() && wxAdminUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("完工到家提醒", homeOrder.ProjectName, "出车任务", orderContent, homeOrder.ArriveDate.ToString("yyyy -MM-dd HH:mm:ss"), $"[{homeOrder.VehicleCode}]号车,{orderVehicleDriverName},{orderVehicleCrewsName}已完工返回"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={homeOrder.Id}&isDriver=false&type=2"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxAdminUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"完工到家提醒{JsonConvert.SerializeObject(result)}"); + } + } + } + + } + } + + } + } + } + #endregion + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/LogAudit/Services/ILogAuditService.cs b/src/Znyc.Dispatching.Application/LogAudit/Services/ILogAuditService.cs new file mode 100644 index 0000000..a0ee123 --- /dev/null +++ b/src/Znyc.Dispatching.Application/LogAudit/Services/ILogAuditService.cs @@ -0,0 +1,6 @@ +namespace Znyc.Dispatching.Application +{ + public interface ILogAuditService + { + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/LogAudit/Services/LogAuditService.cs b/src/Znyc.Dispatching.Application/LogAudit/Services/LogAuditService.cs new file mode 100644 index 0000000..f51884c --- /dev/null +++ b/src/Znyc.Dispatching.Application/LogAudit/Services/LogAuditService.cs @@ -0,0 +1,14 @@ +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Mvc; + +namespace Znyc.Dispatching.Application +{ + /// + /// 审计日志服务 + /// + [ApiDescriptionSettings(Name = "audit", Order = 60, IgnoreApi = true)] + public class LogAuditService : ILogAuditService, IDynamicApiController, ITransient + { + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/LogEx/Services/ILogExService.cs b/src/Znyc.Dispatching.Application/LogEx/Services/ILogExService.cs new file mode 100644 index 0000000..6b8efee --- /dev/null +++ b/src/Znyc.Dispatching.Application/LogEx/Services/ILogExService.cs @@ -0,0 +1,6 @@ +namespace Znyc.Dispatching.Application +{ + public interface ILogExService + { + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/LogEx/Services/LogExService.cs b/src/Znyc.Dispatching.Application/LogEx/Services/LogExService.cs new file mode 100644 index 0000000..aa56e80 --- /dev/null +++ b/src/Znyc.Dispatching.Application/LogEx/Services/LogExService.cs @@ -0,0 +1,22 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Mvc; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Application +{ + /// + /// 异常日志服务 + /// + [ApiDescriptionSettings(Name = "ex", Order = 70, IgnoreApi = true)] + public class LogExService : ILogExService, IDynamicApiController, ITransient + { + private readonly IRepository _repository; + + public LogExService(IRepository repository) + { + _repository = repository; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/LogOp/Services/ILogOpService.cs b/src/Znyc.Dispatching.Application/LogOp/Services/ILogOpService.cs new file mode 100644 index 0000000..39b5200 --- /dev/null +++ b/src/Znyc.Dispatching.Application/LogOp/Services/ILogOpService.cs @@ -0,0 +1,6 @@ +namespace Znyc.Dispatching.Application +{ + public interface ILogOpService + { + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/LogOp/Services/LogOpService.cs b/src/Znyc.Dispatching.Application/LogOp/Services/LogOpService.cs new file mode 100644 index 0000000..fd781f0 --- /dev/null +++ b/src/Znyc.Dispatching.Application/LogOp/Services/LogOpService.cs @@ -0,0 +1,14 @@ +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Mvc; + +namespace Znyc.Dispatching.Application +{ + /// + /// 操作日志服务 + /// + [ApiDescriptionSettings(Name = "op", Order = 80, IgnoreApi = true)] + public class LogOpService : ILogOpService, IDynamicApiController, ITransient + { + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Login/Dto/Input/LoginInput.cs b/src/Znyc.Dispatching.Application/Login/Dto/Input/LoginInput.cs new file mode 100644 index 0000000..1d2adce --- /dev/null +++ b/src/Znyc.Dispatching.Application/Login/Dto/Input/LoginInput.cs @@ -0,0 +1,34 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// 登录实体 + /// + public class LoginInput + { + [Required(ErrorMessage = "JsCode不能为空!")] + public string JsCode { get; set; } + + + /// + /// getuserinfo信息 + /// + [Required(ErrorMessage = "未查询到用户信息")] + public UserInfo UserInfo { get; set; } + } + + public class UserInfo + { + /// + /// 昵称 + /// + public string NickName { get; set; } + + /// + /// 头像地址 + /// + public string AvatarUrl { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Login/Dto/Output/LoginOutput.cs b/src/Znyc.Dispatching.Application/Login/Dto/Output/LoginOutput.cs new file mode 100644 index 0000000..7bdd6e9 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Login/Dto/Output/LoginOutput.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class LoginOutput + { + /// + /// Token + /// + public string Token { get; set; } + + /// + /// 跳转路径 + /// + public string Url { get; set; } + + /// + /// 角色菜单列表 + /// + public List Menus { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Application/Login/Services/ILoginService.cs b/src/Znyc.Dispatching.Application/Login/Services/ILoginService.cs new file mode 100644 index 0000000..f8c82f4 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Login/Services/ILoginService.cs @@ -0,0 +1,14 @@ +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface ILoginService + { + /// + /// 用户登录 + /// + /// + /// + Task Login(LoginInput loginInput); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Login/Services/LoginService.cs b/src/Znyc.Dispatching.Application/Login/Services/LoginService.cs new file mode 100644 index 0000000..35b8e5c --- /dev/null +++ b/src/Znyc.Dispatching.Application/Login/Services/LoginService.cs @@ -0,0 +1,182 @@ +using Furion.DatabaseAccessor; +using Furion.DataEncryption; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using MapsterMapper; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.WeChat.Core.CommonService.TemplateMessage.WxOpen; + +namespace Znyc.Dispatching.Application +{ + /// + /// 登录服务 + /// + [ApiDescriptionSettings(Name = "Login", Order = 146, IgnoreApi = false)] + public class LoginService : ILoginService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _companyRepository; + private readonly IRepository _employeeRepository; + private readonly IUserManager _userManager; + private readonly IRepository _userRepository; + private readonly WeixinSettingOptions _weixinSettingOptions; + private readonly IWxUserRelationService _wxUserRelationService; + private readonly ILogger _logger; + private readonly IRoleMenuService _roleMenuService; + private readonly IMapper _mapper; + + public LoginService( + IRepository userRepository, + IRepository employeeRepository, + IRepository companyRepository, + IUserManager userManager, + ICacheService cacheService, + IOptions weixinSettingOptions, + IWxUserRelationService wxUserRelationService, + ILogger logger, + IMapper mapper, + IRoleMenuService roleMenuService + ) + { + _userRepository = userRepository; + _employeeRepository = employeeRepository; + _companyRepository = companyRepository; + _cacheService = cacheService; + _userManager = userManager; + _weixinSettingOptions = weixinSettingOptions.Value; + _wxUserRelationService = wxUserRelationService; + _logger = logger; + _mapper = mapper; + _roleMenuService = roleMenuService; + } + + /// + /// 用户登录 + /// + /// + /// + [HttpPost] + [UnitOfWork] + [AllowAnonymous] + [Route("api/v1/login")] + public async Task Login(LoginInput loginInput) + { + var jsCode2JsonResult = + await SnsApi.JsCode2JsonAsync(_weixinSettingOptions.WxOpenAppId, _weixinSettingOptions.WxOpenAppSecret, + loginInput.JsCode); + if (jsCode2JsonResult.IsNull()) + { + throw Oops.Bah("jsCode2JsonResult为空"); + } + var user = await _userRepository.Where(x => x.OpenId == jsCode2JsonResult.openid).Select(x => new + { + x.Id, + x.UserName, + x.OpenId + }).FirstOrDefaultAsync(); + + if (user.IsNull()) + { + throw Oops.Bah("您还未注册用户!").StatusCode(4012); + }; + + + var employeeList = await _employeeRepository.Where(x => x.UserId == user.Id && x.Status == (int)CommonStatusEnum.ENABLE).Select(x => new + { + x.UserId, + x.CompanyId, + x.RoleId, + x.Status, + x.IsDefault + }).ToListAsync(); + + if (employeeList.Any(x => x.RoleId == (int)RoleStatusEnum.Outside)) + { + employeeList.Remove(employeeList.Find(x => x.RoleId == (int)RoleStatusEnum.Outside)); + } + var cIds = employeeList.Select(x => x.CompanyId).ToArray(); + //公司 + var company = await _companyRepository.Where(x => cIds.Contains(x.Id) && x.Status == (int)CommonStatusEnum.ENABLE).Select(x => new + { + x.Id, + x.Status + }).OrderByDescending(x => x.Id).FirstOrDefaultAsync(); + + if (company.IsNull()) + { + throw Oops.Bah("").StatusCode(4012); + } + var employee = employeeList.Find(x => x.CompanyId == company.Id); + if (employee.Status == (int)CommonStatusEnum.DISABLE) + { + throw Oops.Bah("此账号已被管理员停用"); + } + + //用户中间表 + await _wxUserRelationService.AddOrUpdateAsync(user.Id, jsCode2JsonResult.openid, jsCode2JsonResult.unionid); + // 生成 token + string accessToken = JWTEncryption.Encrypt(new Dictionary + { + {ClaimConst.CLAINM_USERID, user.Id}, + {ClaimConst.CLAINM_COMPANYID, employee.CompanyId}, + {ClaimConst.CLAINM_ROLEID, employee.RoleId}, + {ClaimConst.CLAINM_USERNAME, user.UserName}, + {ClaimConst.CLAINM_SUPERADMIN, new long[] { (long)RoleStatusEnum.Administrator, (long)RoleStatusEnum.Scheduling,(long)RoleStatusEnum.CarCaptain }.Contains(employee.RoleId)} + }); + //RedisToken + await _cacheService.SetTokenAsync(user.Id, accessToken); + LoginOutput loginOutput = new LoginOutput() + { + Token = accessToken, + Menus = await _roleMenuService.GetRoleMenuListByIdAsync(employee.RoleId) + }; + switch (employee.RoleId) + { + case (long)RoleStatusEnum.Administrator: + case (long)RoleStatusEnum.Scheduling: + case (long)RoleStatusEnum.CarCaptain: + case (long)RoleStatusEnum.Salesman: + case (long)RoleStatusEnum.Financial: + case (long)RoleStatusEnum.WareHouse: + loginOutput.Url = CommonConst.DEFAULT_SUPERADMIN_INDEX; + break; + case (long)RoleStatusEnum.CrewMembers: + case (long)RoleStatusEnum.ProjectPerson: + case (long)RoleStatusEnum.PartTimeSalesman: + loginOutput.Url = CommonConst.DEFAULT_DRIVER_INDEX; + break; + case (long)RoleStatusEnum.Outside: + loginOutput.Url = CommonConst.DEFAULT_OUTSIDE_INDEX; + break; + default: + loginOutput.Url = CommonConst.DEFAULT_DRIVER_INDEX; + break; + } + return loginOutput; + } + + + + + /// + /// 清理缓存 + /// + /// + [HttpGet] + public async Task ClearCache() + { + await _cacheService.RemoveCacheByUserIdAsync(_userManager.UserId); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Mapper/Mapper.cs b/src/Znyc.Dispatching.Application/Mapper/Mapper.cs new file mode 100644 index 0000000..9c9aa51 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Mapper/Mapper.cs @@ -0,0 +1,22 @@ +using Mapster; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Application.Mapper +{ + public class Mapper : IRegister + { + public void Register(TypeAdapterConfig config) + { + config.ForType() + .Map(dest => dest.OrderSourceName, src => typeof(OrderSourceEnum).GetDescription(src.OrderSource)); + + + + config.ForType() + .Map(dest => dest.Picture, src => CommonConst.DEFAULT_ORDERVISA + src.Picture); + + + } + } +} diff --git a/src/Znyc.Dispatching.Application/Menu/Dto/Input/MenuInput.cs b/src/Znyc.Dispatching.Application/Menu/Dto/Input/MenuInput.cs new file mode 100644 index 0000000..4de9dfa --- /dev/null +++ b/src/Znyc.Dispatching.Application/Menu/Dto/Input/MenuInput.cs @@ -0,0 +1,91 @@ +using System.ComponentModel.DataAnnotations; +using Znyc.Dispatching.Core; + +namespace Znyc.Dispatching.Application +{ + /// + /// 菜单参数 + /// + public class MenuInput + { + /// + /// 父Id + /// + public long ParentId { get; set; } + + /// + /// 所属层级 + /// + public int Layers { get; set; } + + /// + /// 名称 + /// + [Required] + [MaxLength(20)] + public string Name { get; set; } + + /// + /// 编码 + /// + [Required] + [MaxLength(50)] + public string Code { get; set; } + + /// + /// 菜单类型(字典 0目录 1菜单 2按钮) + /// + public MenuTypeEnum Type { get; set; } + + /// + /// 图标 + /// + [MaxLength(20)] + public string Icon { get; set; } + + /// + /// 路由地址 + /// + [MaxLength(100)] + public string Router { get; set; } + + /// + /// 权限标识 + /// + public string Permission { get; set; } + + /// + /// 是否外链 + /// + [MaxLength(5)] + public bool IsFrame { get; set; } + + /// + /// 是否展开 + /// + [MaxLength(5)] + public bool IsExpand { get; set; } + + /// + /// 是否显示 + /// + [MaxLength(5)] + public bool IsShow { get; set; } + + /// + /// 排序 + /// + public int Sort { get; set; } + + /// + /// 详细描述 + /// + [MaxLength(100)] + public string Description { get; set; } + + /// + /// CommonStatus + /// + public CommonStatusEnum Status { get; set; } = CommonStatusEnum.ENABLE; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Menu/Dto/OutPut/MenuOutput.cs b/src/Znyc.Dispatching.Application/Menu/Dto/OutPut/MenuOutput.cs new file mode 100644 index 0000000..a224aa5 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Menu/Dto/OutPut/MenuOutput.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + /// + /// 菜单树(列表形式) + /// + public class MenuOutput : MenuInput + { + /// + /// 菜单Id + /// + public long Id { get; set; } + + /// + /// 子集 + /// + public ICollection Childrens { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Menu/Services/IMenuService.cs b/src/Znyc.Dispatching.Application/Menu/Services/IMenuService.cs new file mode 100644 index 0000000..18a541f --- /dev/null +++ b/src/Znyc.Dispatching.Application/Menu/Services/IMenuService.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IMenuService + { + Task> GetLoginPermissionList(long userId); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Menu/Services/MenuService.cs b/src/Znyc.Dispatching.Application/Menu/Services/MenuService.cs new file mode 100644 index 0000000..58d0a33 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Menu/Services/MenuService.cs @@ -0,0 +1,80 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Application +{ + /// + /// 系统菜单服务 + /// + [ApiDescriptionSettings(Name = "menu", Order = 40, IgnoreApi = false)] + public class MenuService : IMenuService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _repository; + private readonly IRepository _roleMenuRepository; + private readonly IRoleMenuService _roleMenuService; + private readonly IRepository _roleRepository; + private readonly IUserManager _userManager; + private readonly IUserRoleService _userRoleService; + + public MenuService(IRepository repository, + IRepository roleMenuRepository, + ICacheService cacheService, + IUserManager userManager, + IUserRoleService userRoleService, + IRoleMenuService roleMenuService, + IRepository roleRepository) + { + _repository = repository; + _cacheService = cacheService; + _userManager = userManager; + _userRoleService = userRoleService; + _roleMenuService = roleMenuService; + _roleMenuRepository = roleMenuRepository; + _roleRepository = roleRepository; + } + + /// + /// 获取用户权限(按钮权限标识集合) + /// + /// + /// + [NonAction] + public async Task> GetLoginPermissionList(long userId) + { + List permissions = await _cacheService.GetPermissionAsync(userId); // 先从缓存里面读取 + if (permissions.IsNull() || permissions.Count < 1) + { + if (!_userManager.SuperAdmin) + { + List roleIdList = await _userRoleService.GetUserRoleIdList(userId); + List menuIdList = await _roleMenuService.GetRoleMenuIdList(roleIdList); + permissions = await _repository.Where(u => menuIdList.Contains(u.Id)) + .Where(u => u.Type == MenuTypeEnum.BTN) + .Where(u => u.Status == CommonStatusEnum.ENABLE) + .Select(u => u.Permission).ToListAsync(); + } + else + { + permissions = await _repository.DetachedEntities + .Where(u => u.Type == MenuTypeEnum.BTN) + .Where(u => u.Status == CommonStatusEnum.ENABLE) + .Select(u => u.Permission).ToListAsync(); + } + + await _cacheService.SetPermissionAsync(userId, permissions); // 缓存结果 + } + + return permissions; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Message/Dto/Input/MessageAddInput.cs b/src/Znyc.Dispatching.Application/Message/Dto/Input/MessageAddInput.cs new file mode 100644 index 0000000..bf8e8e9 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Message/Dto/Input/MessageAddInput.cs @@ -0,0 +1,27 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// + public class MessageAddInput + { + /// + /// 消息标题 + /// + [Required] + [MaxLength(12)] + public string MessageTitle { get; set; } + + /// + /// 产品类型 + /// + public int ProductType { get; set; } + + /// + /// 消息内容 + /// + [Required] + public string Content { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Message/Dto/OutPut/MessageOutput.cs b/src/Znyc.Dispatching.Application/Message/Dto/OutPut/MessageOutput.cs new file mode 100644 index 0000000..a2da52f --- /dev/null +++ b/src/Znyc.Dispatching.Application/Message/Dto/OutPut/MessageOutput.cs @@ -0,0 +1,27 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class MessageOutput + { + /// + /// 主键 + /// + public long Id { get; set; } + + /// + /// 消息类型 + /// + public int MessageType { get; set; } + + /// + /// 消息标题 + /// + public string MessageTitle { get; set; } + + /// + /// 消息内容 + /// + public string Content { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Message/Services/IMessageService.cs b/src/Znyc.Dispatching.Application/Message/Services/IMessageService.cs new file mode 100644 index 0000000..126495a --- /dev/null +++ b/src/Znyc.Dispatching.Application/Message/Services/IMessageService.cs @@ -0,0 +1,6 @@ +namespace Znyc.Dispatching.Application +{ + public interface IMessageService + { + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Message/Services/MessageService.cs b/src/Znyc.Dispatching.Application/Message/Services/MessageService.cs new file mode 100644 index 0000000..ce67879 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Message/Services/MessageService.cs @@ -0,0 +1,61 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Application +{ + /// + /// 站内消息服务 + /// + [ApiDescriptionSettings(Name = "message", Order = 110)] + public class MessageService : IMessageService, IDynamicApiController, ITransient + { + private readonly IRepository _repository; + + public MessageService(IRepository repository) + { + _repository = repository; + } + + /// + /// 分页查询系统消息通知 + /// + /// + /// + /// + /// + [HttpGet] + public async Task> PageAsync(int messageType, int currentPage = 1, int pageSize = 10) + { + PagedList pageList = await _repository + .Where(x => x.Type == 1 && x.MessageType == messageType) + .OrderByDescending(x => x.SendTime) + .ToPagedListAsync(currentPage, pageSize); + return pageList; + } + + /// + /// 获取消息通知详情 + /// + /// + /// + [HttpGet] + public async Task GetMessageById(long id) + { + Message result = await _repository.FindOrDefaultAsync(id); + if (result.IsNull()) + { + throw Oops.Oh("消息通知不存在"); + } + + return result; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/MessageRecord/Dto/Input/MessageRecordAddInput.cs b/src/Znyc.Dispatching.Application/MessageRecord/Dto/Input/MessageRecordAddInput.cs new file mode 100644 index 0000000..77aaa79 --- /dev/null +++ b/src/Znyc.Dispatching.Application/MessageRecord/Dto/Input/MessageRecordAddInput.cs @@ -0,0 +1,23 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// 消息记录 + /// + public class MessageRecordAddInput + { + /// + /// 接收者Id + /// + public long ReceiverId { get; set; } + + /// + /// 消息Id + /// + public long MessageId { get; set; } + + /// + /// 状态 + /// + public int Status { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/MessageRecord/Dto/OutPut/MessageRecordOutput.cs b/src/Znyc.Dispatching.Application/MessageRecord/Dto/OutPut/MessageRecordOutput.cs new file mode 100644 index 0000000..0361256 --- /dev/null +++ b/src/Znyc.Dispatching.Application/MessageRecord/Dto/OutPut/MessageRecordOutput.cs @@ -0,0 +1,22 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class MessageRecordOutput + { + /// + /// 主键 + /// + public long Id { get; set; } + + /// + /// 消息标题 + /// + public string MessageTitle { get; set; } + + /// + /// 消息内容 + /// + public string Content { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/MessageRecord/Services/IMessageRecordService.cs b/src/Znyc.Dispatching.Application/MessageRecord/Services/IMessageRecordService.cs new file mode 100644 index 0000000..4bc835a --- /dev/null +++ b/src/Znyc.Dispatching.Application/MessageRecord/Services/IMessageRecordService.cs @@ -0,0 +1,6 @@ +namespace Znyc.Dispatching.Application +{ + public interface IMessageRecordService + { + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/MessageRecord/Services/MessageRecordService.cs b/src/Znyc.Dispatching.Application/MessageRecord/Services/MessageRecordService.cs new file mode 100644 index 0000000..82ae425 --- /dev/null +++ b/src/Znyc.Dispatching.Application/MessageRecord/Services/MessageRecordService.cs @@ -0,0 +1,31 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Mvc; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Application +{ + /// + /// 消息记录服务 + /// + [ApiDescriptionSettings(Name = "messagerecord", Order = 120, IgnoreApi = true)] + public class MessageRecordService : IMessageRecordService, IDynamicApiController, ITransient + { + private readonly IRepository _messageRepository; + private readonly IRepository _repository; + private readonly IUserManager _userManager; + + public MessageRecordService( + IRepository repository, + IUserManager userManager, + IRepository messageRepository + ) + { + _repository = repository; + _userManager = userManager; + _messageRepository = messageRepository; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Oil/Dto/Input/OilAddInput.cs b/src/Znyc.Dispatching.Application/Oil/Dto/Input/OilAddInput.cs new file mode 100644 index 0000000..ee61730 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Oil/Dto/Input/OilAddInput.cs @@ -0,0 +1,51 @@ +using System; +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// + /// + public class OilAddInput + { + /// + /// 加油日期 + /// + [Required(ErrorMessage = "请选择加油日期")] + public DateTime PlusOilDate { get; set; } + + /// + /// 车辆Id + /// + [Required(ErrorMessage = "请选择车辆编号")] + public long VehicleId { get; set; } + + /// + /// 车俩编号 + /// + [Required(ErrorMessage = "请选择车辆编号")] + public string VehicleCode { get; set; } + + /// + /// 加油单号 + /// + public string PlusOilOrder { get; set; } + + /// + /// 加油量 + /// + [Required(ErrorMessage = "请填写加油量")] + [MaxLength(10, ErrorMessage = "加油量输入不正确")] + public string PlusOilAmount { get; set; } + + /// + /// 油单价 + /// + public decimal OilPrice { get; set; } + + /// + /// 金额 + /// + public decimal AmountMoney { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Oil/Dto/Input/OilUpdateInput.cs b/src/Znyc.Dispatching.Application/Oil/Dto/Input/OilUpdateInput.cs new file mode 100644 index 0000000..3d3ecf0 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Oil/Dto/Input/OilUpdateInput.cs @@ -0,0 +1,9 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class OilUpdateInput : OilAddInput + { + public long Id { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Oil/Dto/OutPut/CensusOilOutput.cs b/src/Znyc.Dispatching.Application/Oil/Dto/OutPut/CensusOilOutput.cs new file mode 100644 index 0000000..d3e353a --- /dev/null +++ b/src/Znyc.Dispatching.Application/Oil/Dto/OutPut/CensusOilOutput.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + /// + /// 油耗统计 + /// + public class CensusOilListOutput + { + /// + /// 主键 + /// + public long VehicleId { get; set; } + + /// + /// 车俩编号 + /// + public string VehicleCode { get; set; } + + /// + /// 加油量 + /// + public string PlusOilAmount { get; set; } + + /// + /// 金额 + /// + public decimal AmountMoney { get; set; } + + /// + /// 加油次数 + /// + public int PlusOilCount { get; set; } + } + + + public class CensusOilOutput + { + /// + /// 加油总次数 + /// + public int AllPlusOilCount { get; set; } + + /// + /// 加油总量 + /// + public int AllPlusOilAmount { get; set; } + + /// + /// 总金额 + /// + public decimal AllAmountMoney { get; set; } + + /// + /// 油耗统计 + /// + public List CensusOilList { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Oil/Dto/OutPut/OilOutput.cs b/src/Znyc.Dispatching.Application/Oil/Dto/OutPut/OilOutput.cs new file mode 100644 index 0000000..2fa0068 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Oil/Dto/OutPut/OilOutput.cs @@ -0,0 +1,42 @@ +namespace Znyc.Dispatching.Application +{ + public class OilOutput + { + /// + /// 主键 + /// + public long Id { get; set; } + + public long VehicleId { get; set; } + + /// + /// 加油日期 + /// + public string PlusOilDate { get; set; } + + /// + /// 车俩编号 + /// + public string VehicleCode { get; set; } + + /// + /// 加油单号 + /// + public string PlusOilOrder { get; set; } + + /// + /// 加油量 + /// + public string PlusOilAmount { get; set; } + + /// + /// 油单价 + /// + public decimal OilPrice { get; set; } + + /// + /// 金额 + /// + public decimal AmountMoney { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Oil/Services/IOilService.cs b/src/Znyc.Dispatching.Application/Oil/Services/IOilService.cs new file mode 100644 index 0000000..57f68d9 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Oil/Services/IOilService.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + /// + /// 油耗服务 + /// + public interface IOilService + { + + /// + /// 加油记录 + /// + /// + /// + /// + /// + /// + Task> PlusOilPageAsync(int currentPage, int pageSize, DateTime startTime, DateTime endTime); + + /// + /// 油耗统计 + /// + /// + /// + /// + Task OilCensusPageAsync(DateTime startTime, DateTime endTime); + + /// + /// 根据Id获油耗信息 + /// + /// + Task GetByIdAsync(long companyId); + + /// + /// 添加油耗信息 + /// + /// + /// + Task InsertAsync(OilAddInput input); + + /// + /// 修改油耗信息 + /// + /// + /// + Task UpdateAsync(OilUpdateInput input); + + /// + /// 删除油耗信息 + /// + /// + /// + Task DeleteAsync(long oilId); + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Oil/Services/OilService.cs b/src/Znyc.Dispatching.Application/Oil/Services/OilService.cs new file mode 100644 index 0000000..c252534 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Oil/Services/OilService.cs @@ -0,0 +1,169 @@ +using Furion.DatabaseAccessor; +using Furion.DatabaseAccessor.Extensions; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Mapster; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Application +{ + /// + /// 油耗管理 + /// + [ApiDescriptionSettings(Name = "oil", Order = 30)] + public class OilService : IOilService, IDynamicApiController, ITransient + { + private readonly IRepository _repository; + private readonly IUserManager _userManager; + + public OilService( + IRepository repository, + IUserManager userManager + ) + { + _repository = repository; + _userManager = userManager; + } + + + /// + /// 加油记录 + /// + /// + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/plus/oils/search")] + public async Task> PlusOilPageAsync(int currentPage, int pageSize, DateTime startTime, DateTime endTime) + { + var oils = (await _repository.DetachedEntities + .Where(x => x.CompanyId == _userManager.CompanyId && x.IsDeleted == false) + .Where(startTime.IsNotNull(), x => x.CreatedTime >= startTime) + .Where(endTime.IsNotNull(), x => x.CreatedTime <= endTime) + .OrderByDescending(x => x.PlusOilDate) + .Select(x => new OilOutput() + { + Id = x.Id, + VehicleId = x.VehicleId, + PlusOilDate = x.PlusOilDate.ToString("yyyy-MM-dd"), + VehicleCode = x.VehicleCode, + PlusOilOrder = x.PlusOilOrder, + PlusOilAmount = x.PlusOilAmount, + OilPrice = x.OilPrice, + AmountMoney = x.AmountMoney + }) + .ToPagedListAsync(currentPage, pageSize)).Adapt>(); + return oils; + } + + /// + /// 油耗统计 + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/census/oils/search")] + public async Task OilCensusPageAsync(DateTime startTime, DateTime endTime) + { + var oilList = await @"SELECT VehicleCode,VehicleId, + Count(CASE WHEN IsDeleted=FALSE THEN VehicleId END) AS PlusOilCount, + SUM(AmountMoney) AS AmountMoney, + SUM(PlusOilAmount)AS PlusOilAmount + FROM dc_oil WHERE CompanyId = @companyId AND IsDeleted=FALSE AND VehicleId > 0 And PlusOilDate >= @startTime And PlusOilDate <= @endTime + GROUP BY VehicleId,VehicleCode + ORDER BY PlusOilCount DESC,PlusOilAmount DESC,AmountMoney DESC" + .SqlQueryAsync(new { companyId = _userManager.CompanyId, startTime = startTime, endTime = endTime }); + CensusOilOutput data = new CensusOilOutput() { CensusOilList = oilList }; + foreach (var item in oilList) + { + data.AllPlusOilCount += item.PlusOilCount; + data.AllPlusOilAmount += item.PlusOilAmount.ObjToInt(); + data.AllAmountMoney += item.AmountMoney; + } + return data; + } + + /// + /// 根据Id获油耗信息 + /// + /// + [HttpGet] + [Route("api/v1/oil/{id}")] + public async Task GetByIdAsync(long id) + { + Oil oil = await _repository.DetachedEntities.FirstOrDefaultAsync(x => x.Id == id); + var result = oil.Adapt(); + result.PlusOilDate = oil.PlusOilDate.ToString("yyyy-MM-dd"); + return result; + } + + + /// + /// 添加油耗信息 + /// + /// + /// + [HttpPost] + [Route("api/v1/oil")] + public async Task InsertAsync(OilAddInput input) + { + var oil = input.Adapt(); + oil.CompanyId = _userManager.CompanyId; + var result = await _repository.InsertNowAsync(oil); + if (result.IsNull()) + { + throw Oops.Oh("添加油耗信息失败"); + } + } + + /// + /// 修改油耗信息 + /// + /// + /// + [HttpPut] + [Route("api/v1/oil")] + public async Task UpdateAsync(OilUpdateInput input) + { + var oil = await _repository.FirstOrDefaultAsync(x => x.Id == input.Id); + if (oil.IsNull()) throw Oops.Oh("暂无该信息"); + var result = await _repository.UpdateNowAsync(input.Adapt(oil)); + if (result.IsNull()) + { + throw Oops.Oh("修改油耗信息失败"); + } + } + + /// + /// 删除油耗信息 + /// + /// + /// + [HttpDelete] + [Route("api/v1/oil/{id}")] + public async Task DeleteAsync(long id) + { + var oil = await _repository.FirstOrDefaultAsync(x => x.Id == id); + if (oil.IsNull()) throw Oops.Oh("暂无该信息"); + oil.IsDeleted = true; + var result = await _repository.UpdateNowAsync(oil); + if (result.IsNull()) + { + throw Oops.Oh("删除油耗信息失败"); + } + } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/Input/Assign/AssignOrderInput.cs b/src/Znyc.Dispatching.Application/Order/Dto/Input/Assign/AssignOrderInput.cs new file mode 100644 index 0000000..13b1c27 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/Input/Assign/AssignOrderInput.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + /// + /// 指派订单实体 + /// + public class AssignOrderInput : StayAssignInput + { + + /// + /// OrderId + /// + public long Id { get; set; } + + /// + /// 车辆Id + /// + public long VehicleId { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + + /// + /// 是否外请车 + /// + public bool IsOutside { get; set; } + + /// + /// 车组人员 + /// + public string OrderVehiclePerson { get; set; } + + + /// + /// 是否替换车组人员 + /// + public bool IsReplaceOrderVehicle { get; set; } + + + /// + /// 车组人员 + /// + public List OrderVehicles { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/Input/Assign/AssignUpdateInput.cs b/src/Znyc.Dispatching.Application/Order/Dto/Input/Assign/AssignUpdateInput.cs new file mode 100644 index 0000000..7f985ef --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/Input/Assign/AssignUpdateInput.cs @@ -0,0 +1,14 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// 指派订单实体 + /// + public class AssignUpdateInput : AssignOrderInput + { + /// + /// OrderId + /// + public long Id { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/Input/OrderAddInput.cs b/src/Znyc.Dispatching.Application/Order/Dto/Input/OrderAddInput.cs new file mode 100644 index 0000000..d938506 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/Input/OrderAddInput.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// 派单订单表实体 + /// + public class OrderAddInput + { + + #region 待指派 + + /// + /// 工程Id + /// + [Required(ErrorMessage = "请选择工程")] + public long ProjectId { get; set; } + + /// + /// 工程名称 + /// + public string ProjectName { get; set; } + + /// + /// 业务员Id + /// + public long SalesmanId { get; set; } + + /// + /// 到场时间 + /// + [Required(ErrorMessage = "请选择到场时间")] + public DateTime ArriveDate { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + [Required(ErrorMessage = "请选择所在位置")] + public string Address { get; set; } + + /// + /// 订单内容 + /// + [Required(ErrorMessage = "请输入派单内容")] + public string OrderContent { get; set; } + #endregion + + + + #region 一键指派 + + /// + /// 车辆Id + /// + public long VehicleId { get; set; } + + /// + /// 是否外请车 + /// + public bool IsOutside { get; set; } + + /// + /// 车组人员 + /// + public List orderVehicles { get; set; } + + #endregion + + /// + /// 任务车型 + /// + public long VehicleType { get; set; } + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/Input/OrderUpdateInput.cs b/src/Znyc.Dispatching.Application/Order/Dto/Input/OrderUpdateInput.cs new file mode 100644 index 0000000..8296862 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/Input/OrderUpdateInput.cs @@ -0,0 +1,9 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class OrderUpdateInput : OrderAddInput + { + public long Id { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/Input/Sign/SignInput.cs b/src/Znyc.Dispatching.Application/Order/Dto/Input/Sign/SignInput.cs new file mode 100644 index 0000000..1974516 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/Input/Sign/SignInput.cs @@ -0,0 +1,23 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// 签单 + /// + public class SignInput + { + + /// + /// OrderId + /// + public long OrderId { get; set; } + + + /// + /// 图片路径 + /// + [Required(ErrorMessage = "请上传签证单")] + public string Picture { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/Input/Sign/SignUpdateInput.cs b/src/Znyc.Dispatching.Application/Order/Dto/Input/Sign/SignUpdateInput.cs new file mode 100644 index 0000000..47d0f50 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/Input/Sign/SignUpdateInput.cs @@ -0,0 +1,10 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// 签单 + /// + public class SignUpdateInput : SignInput + { + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/Input/StayAssign/StayAssignInput.cs b/src/Znyc.Dispatching.Application/Order/Dto/Input/StayAssign/StayAssignInput.cs new file mode 100644 index 0000000..7d1e09d --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/Input/StayAssign/StayAssignInput.cs @@ -0,0 +1,70 @@ +using System; +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// 待指派订单实体 + /// + public class StayAssignInput + { + public long Id { get; set; } + + /// + /// 工程Id + /// + public long ProjectId { get; set; } + + /// + /// 工程名称 + /// + public string ProjectName { get; set; } + + /// + /// 业务员Id + /// + public long SalesmanId { get; set; } + + /// + /// 到场时间 + /// + [Required(ErrorMessage = "请选择到场时间")] + public DateTime ArriveDate { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 订单内容 + /// + public string OrderContent { get; set; } + + /// + /// 任务车型 + /// + public long VehicleType { get; set; } + + + /// + /// 施工单位 + /// + public long ConstructionId { get; set; } + + /// + /// 施工单位 + /// + public string ConstructionName { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/Input/StayAssign/StayAssignUpdateInput.cs b/src/Znyc.Dispatching.Application/Order/Dto/Input/StayAssign/StayAssignUpdateInput.cs new file mode 100644 index 0000000..055c146 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/Input/StayAssign/StayAssignUpdateInput.cs @@ -0,0 +1,14 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// 待指派订单实体 + /// + public class StayAssignUpdateInput : StayAssignInput + { + /// + /// OrderId + /// + public long Id { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/OutPut/AdminOrderListOutput.cs b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/AdminOrderListOutput.cs new file mode 100644 index 0000000..0e7eba1 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/AdminOrderListOutput.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + /// + /// 订单列表返回 + /// + public class AdminOrderListOutput + { + public int StayAssignCount { get; set; } + public int AssignCount { get; set; } + public int CompleteCount { get; set; } + public int EvaluateCount { get; set; } + public PagedList PagedList { get; set; } + + } +} diff --git a/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderListOutput.cs b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderListOutput.cs new file mode 100644 index 0000000..1c2bd95 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderListOutput.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + /// + /// 订单列表返回 + /// + public class OrderListOutput + { + /// + /// OrderId + /// + public long Id { get; set; } + + /// + /// 车辆Id,,冗余查询车辆列表状态 + /// + public long VehicleId { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 订单标题 + /// + public string OrderTitle { get; set; } + + /// + /// 订单内容 + /// + public string OrderContent { get; set; } + + /// + /// 到场时间 + /// + public DateTime ArriveDate { get; set; } + + /// + /// 订单来源 + /// + public int OrderSource { get; set; } + + /// + /// 订单来源明细 + /// + public string OrderSourceName { get; set; } + + + /// + /// 是否外请车 + /// + public bool IsOutside { get; set; } + /// + /// 状态, + /// + public int Status { get; set; } + + /// + /// 状态名称 + /// + public string StatusName { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 工程Id + /// + public long ProjectId { get; set; } + + /// + /// 工程名称 + /// + public string ProjectName { get; set; } + + /// + /// 车组人员 + /// + public string OrderVehiclePerson { get; set; } + + /// + /// + /// + public List OrderVehicles { get; set; } + + + /// + /// 车组人员姓名 + /// + public string OrderVehicleDriverName { get; set; } + + + /// + /// 车组人员电话 + /// + public string OrderVehicleDriverPhone { get; set; } + + /// + /// 指派人名称 + /// + public string AssignUserName { get; set; } + + /// + /// 指派人Id + /// + public long AssignUserId { get; set; } + + /// + /// 任务车型 + /// + public long VehicleType { get; set; } + + + /// + /// 任务车型名称 + /// + public string VehicleTypeName { get; set; } + + + /// + /// 距离 + /// + public string Distance { get; set; } + + + + /// + /// 预计到到时间 + /// + public string ExpectArriveDate { get; set; } + + } +} diff --git a/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderOutput.cs b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderOutput.cs new file mode 100644 index 0000000..b5fc6ec --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderOutput.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + /// + /// + /// + public class OrderOutput + { + + /// + /// OrderId + /// + public long Id { get; set; } + + /// + /// 车辆Id + /// + public long VehicleId { get; set; } + + + /// + /// 车俩编号 + /// + public string VehicleCode { get; set; } + + + /// + /// 工程Id + /// + public long ProjectId { get; set; } + + + /// + /// 工程名称 + /// + public string ProjectName { get; set; } + + /// + /// 业务员Id + /// + public long SalesmanId { get; set; } + + /// + /// 到场时间 + /// + public DateTime ArriveDate { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + + /// + /// 订单标题 + /// + public string OrderTitle { get; set; } + + + /// + /// 订单内容 + /// + public string OrderContent { get; set; } + + /// + /// 状态,,10=待指派,20=已指派,未接单,30=已接单,40=已出发,50=已完成(已签单),60=已离开,70=已评价 + /// + public int Status { get; set; } + + /// + /// 状态 + /// + public string StatusName { get; set; } + + /// + /// 订单来源,10=录入,20=报单 + /// + public int OrderSource { get; set; } + + /// + /// 订单来源 + /// + public string OrderSourceName { get; set; } + + ///// + ///// 指派时间 + ///// + //public DateTime? AssignDate { get; set; } + + ///// + ///// 指派人 + ///// + //public long AssignUserId { get; set; } + + ///// + ///// 接单时间 + ///// + //public DateTime? ReceiveDate { get; set; } + + ///// + ///// 出发时间 + ///// + //public DateTime? TravelDate { get; set; } + + + ///// + ///// 到达时间 + ///// + //public DateTime? AppearDate { get; set; } + + ///// + ///// 签单时间 + ///// + //public DateTime? SignDate { get; set; } + + + ///// + ///// 完成时间 + ///// + //public DateTime? CompleteDate { get; set; } + + ///// + ///// 评价时间 + ///// + //public DateTime? EvaluateDate { get; set; } + + ///// + ///// 离开时间 + ///// + //public DateTime? LeaveDate { get; set; } + + + /// + /// 车组人员 + /// + public string OrderVehiclePerson { get; set; } + + + public List> OrderStatusDates { get; set; } + + /// + /// 车组人员信息 + /// + public List OrderVehicles { get; set; } + + + /// + /// 签证明细 + /// + public List OrderVisas { get; set; } + + /// + /// 是否外请车 + /// + public bool IsOutside { get; set; } + + + /// + /// + /// + public long VehicleType { get; set; } + + + /// + /// + /// + public string VehicleTypeName { get; set; } + + /// + /// 距离 + /// + public string Distance { get; set; } + + + + /// + /// 预计到到时间 + /// + public string ExpectArriveDate { get; set; } + + + /// + /// 施工单位 + /// + public long ConstructionId { get; set; } + + /// + /// 施工单位 + /// + public string ConstructionName { get; set; } + /// + /// 到家时间 + /// + public DateTime? ArriveHomeDate { get; set; } + + } + + /// + /// + /// + public class OrderStatusDate + { + /// + /// + /// + public string StatusName { get; set; } + + /// + /// + /// + public DateTime? DateTime { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderStatisticsConstructionOutput.cs b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderStatisticsConstructionOutput.cs new file mode 100644 index 0000000..75f2da1 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderStatisticsConstructionOutput.cs @@ -0,0 +1,53 @@ + +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class OrderStatisticsConstructionOutput + { + public long ConstructionId { get; set; } + + // public string ConstructionName { get; set; } + + // public long ProjectId { get; set; } + + public string ProjectName { get; set; } + /// + /// 派单量 + /// + public long AssignCount { get; set; } + /// + /// 完成量 + /// + public long CompleteCount { get; set; } + + /// + /// 服务评价 + /// + public double Evaluation { get; set; } + + } + + public class OrderStatisticsConstructionOutputs + { + public string ConstructionName { get; set; } + /// + /// 派单量 + /// + public long AssignCount { get; set; } + /// + /// 完成量 + /// + public long CompleteCount { get; set; } + + /// + /// 服务评价 + /// + public double Evaluation { get; set; } + + public List Projects { get; set; } + } + + + +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderStatisticsOutput.cs b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderStatisticsOutput.cs new file mode 100644 index 0000000..a21ec49 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Dto/OutPut/OrderStatisticsOutput.cs @@ -0,0 +1,53 @@ + +namespace Znyc.Dispatching.Application +{ + public class OrderStatisticsOutput + { + public long VehicleId { get; set; } + + public long ProjectId { get; set; } + + public long UserId { get; set; } + + /// + /// 设备号 + /// + public string VehicleCode { get; set; } + + /// + /// 项目名称 + /// + public string ProjectName { get; set; } + + /// + /// 员工姓名 + /// + public string UserName { get; set; } + + /// + /// 派单量 + /// + public int AssignCount { get; set; } + + /// + /// 接单量 + /// + public int ReceiveCount { get; set; } + + /// + /// 完成量 + /// + public int CompleteCount { get; set; } + + /// + /// 服务评价 + /// + public double Evaluation { get; set; } + + #region V1.2.7 + + public long ConstructionId { get; set; } + + #endregion + } +} diff --git a/src/Znyc.Dispatching.Application/Order/Services/IOrderService.cs b/src/Znyc.Dispatching.Application/Order/Services/IOrderService.cs new file mode 100644 index 0000000..b963777 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Services/IOrderService.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IOrderService + { + #region 回单查询 + + /// + /// 回单查询列表 + /// + /// 0全部,1未接单,2已结单,3已完成,4已评价 + /// + /// + /// + /// + /// + /// + Task> ReceiptPageAsync(DateTime startTime, DateTime endTime, int status = 0, int currentPage = 1, int pageSize = 10, string key = ""); + #endregion + + #region 任务统计 + /// + /// 任务统计--车辆 + /// + /// + /// + /// + /// + /// + Task> GetOrderStatisticsByVehicleAsync(DateTime startTime, DateTime endTime, int currentPage = 1, int pageSize = 10); + + /// + /// 任务统计--工程 + /// + /// + /// + /// + /// + /// + Task> GetOrderStatisticsByProjectAsync(DateTime startTime, DateTime endTime, int currentPage = 1, int pageSize = 10); + + /// + /// 任务统计--人员 + /// + /// + /// + /// + /// + /// + Task> GetOrderStatisticsByEmployeeAsync(DateTime startTime, DateTime endTime, int currentPage = 1, int pageSize = 10); + #endregion + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Order/Services/OrderService.cs b/src/Znyc.Dispatching.Application/Order/Services/OrderService.cs new file mode 100644 index 0000000..4964b6d --- /dev/null +++ b/src/Znyc.Dispatching.Application/Order/Services/OrderService.cs @@ -0,0 +1,1644 @@ +using Furion.ClayObject; +using Furion.DatabaseAccessor; +using Furion.DatabaseAccessor.Extensions; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Mapster; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Newtonsoft.Json; +using Senparc.Weixin.MP.AdvancedAPIs; +using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Common.Extensions; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Helpers; +using Znyc.Dispatching.MongoDb.Repository.Repositorys; +using Znyc.Dispatching.WeChat.Core.CommonService.TemplateMessage; + + +namespace Znyc.Dispatching.Application +{ + /// + /// 派工订单管理 + /// + [ApiDescriptionSettings(Name = "order", Order = 32)] + public class OrderService : IOrderService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _repository; + private readonly IUserManager _userManager; + private readonly IRepository _orderVehicleRepository; + private readonly IRepository _vehicleRepository; + private readonly IRepository _orderVisaRepository; + private readonly WeixinSettingOptions _weixinSettingOptions; + private readonly IRepository _wxUserRelationRepository; + private readonly IGpsRealTimeRepository _gpsRealTimeRepository; + private readonly IRepository _companyRepository; + private readonly IRepository _userRepository; + private readonly IEmployeeService _employeeService; + private readonly IRepository _vehiclePersonitory; + private readonly ILogger _logger; + private readonly IRepository _projectPersonRepository; + private readonly IRepository _vehicleTypeRepository; + private readonly IRepository _constructionRpository; + private readonly IRepository _employeeRepository; + private readonly IRepository _projectRepository; + + public OrderService( + IUserManager userManager, + ICacheService cacheService, + IRepository repository, + IRepository orderVisaRepository, + IRepository vehicleRepository, + IRepository orderVehicleRepository, + IOptions weixinSettingOptions, + IRepository wxUserRelationRepository, + IGpsRealTimeRepository gpsRealTimeRepository, + IRepository companyRepository, + IRepository userRepository, + IEmployeeService employeeService, + IRepository vehiclePersonitory, + ILogger logger, + IRepository projectPersonRepository, + IRepository vehicleTypeRepository, + IRepository constructionRpository, + IRepository employeeRepository, + IRepository projectRepository) + { + _repository = repository; + _userManager = userManager; + _cacheService = cacheService; + _vehicleRepository = vehicleRepository; + _orderVisaRepository = orderVisaRepository; + _orderVehicleRepository = orderVehicleRepository; + _weixinSettingOptions = weixinSettingOptions.Value; + _wxUserRelationRepository = wxUserRelationRepository; + _gpsRealTimeRepository = gpsRealTimeRepository; + _companyRepository = companyRepository; + _userRepository = userRepository; + _employeeService = employeeService; + _vehiclePersonitory = vehiclePersonitory; + _logger = logger; + _projectPersonRepository = projectPersonRepository; + _vehicleTypeRepository = vehicleTypeRepository; + _constructionRpository = constructionRpository; + _employeeRepository = employeeRepository; + _projectRepository = projectRepository; + } + + + #region 管理员/调度端/业务员端 + + /// + /// 管理端任务列表 + /// + /// + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/admin/orders/search")] + public async Task PageAsync(int status = 0, int currentPage = 1, int pageSize = 10, string key = "") + { + + //所有订单 + var allOrders = _repository.Where(x => x.CompanyId == _userManager.CompanyId && !new int[] { (int)OrderStatus.Cancel }.Contains(x.Status)).ToList(); + + var orders = allOrders + .WhereIf(status == 1, x => x.Status == (int)OrderStatus.StayAssign) + .WhereIf(status == 2, x => new int[] { (int)OrderStatus.Assign, (int)OrderStatus.Receive, (int)OrderStatus.Travel, (int)OrderStatus.Appear }.Contains(x.Status)) + .WhereIf(status == 3, x => new int[] { (int)OrderStatus.Complete, (int)OrderStatus.Leave, (int)OrderStatus.Sign, (int)OrderStatus.ArriveHome }.Contains(x.Status)) + .WhereIf(status == 4, x => x.Status == (int)OrderStatus.Evaluate) + .WhereIf(new long[] { (long)RoleStatusEnum.Salesman, (long)RoleStatusEnum.PartTimeSalesman }.Contains(_userManager.RoleId), + x => x.CreatedUserId == _userManager.UserId || x.SalesmanId == _userManager.UserId) + .WhereIf(key.IsNotNull(), x => x.OrderVehiclePerson.Contains(key) || x.VehicleCode.Contains(key) || x.OrderContent.Contains(key) || x.ProjectName.Contains(key)) + .OrderByDescending(x => x.ArriveDate) + .Skip((currentPage - 1) * pageSize) + .Take(pageSize) + .ToList().Adapt>(); + + + if (orders.IsNotNull() && orders.Count > 0) + { + //查询车组司机列表 + var orderVehicles = await _orderVehicleRepository.Where(x => orders.Select(x => x.Id).Contains(x.OrderId) && x.IsDriver == true).ToListAsync(); + var users = await _userRepository.Where(x => orders.Select(x => x.VehicleId).Contains(x.Id)).ToListAsync(); + //查询所有车型 + var vehicleTypes = _vehicleTypeRepository.DetachedEntities.Where(x => x.CompanyId == _userManager.CompanyId).ToList(); + //车辆Gps + var gpsRealTimes = await _gpsRealTimeRepository.GetGpsRealTimeByCompanyId(_userManager.CompanyId); + + foreach (var order in orders) + { + //外请车,车辆Id等于UserId + if (order.IsOutside) + { + if (users.IsNotNull() && users.Count > 0) + { + order.OrderVehicleDriverName = users.Where(x => x.Id == order.VehicleId).FirstOrDefault()?.UserName; + order.OrderVehicleDriverPhone = users.Where(x => x.Id == order.VehicleId).FirstOrDefault()?.Phone; + } + } + else + { + if (orderVehicles.IsNotNull() && orderVehicles.Count > 0) + { + order.OrderVehicleDriverName = orderVehicles.Where(x => x.OrderId == order.Id).FirstOrDefault()?.UserName; + order.OrderVehicleDriverPhone = orderVehicles.Where(x => x.OrderId == order.Id).FirstOrDefault()?.UserPhone; + } + } + order.StatusName = typeof(OrderStatus).GetDescription(order.Status); + string vehicleTypeName = ""; + if (order.VehicleType > 0) + { + vehicleTypeName = vehicleTypes.Where(x => x.Id == order.VehicleType).FirstOrDefault()?.Name; + } + order.VehicleTypeName = vehicleTypeName; + order.OrderTitle = order.ProjectName.IsNull() ? (order.OrderContent.Length >= 13 ? order.OrderContent.Substring(0, 13).Trim().ToString() : order.OrderContent.Trim()) : (order.ProjectName.Length >= 13 ? order.ProjectName.Substring(0, 13).Trim().ToString() : order.ProjectName.Trim()); + + //查询当前车辆是否有任务 + try + { + if (new long[] { (long)OrderStatus.Receive, (long)OrderStatus.Travel }.Contains(order.Status)) + { + var gpsRealTime = gpsRealTimes.FirstOrDefault(x => x.VehicleId == order.VehicleId); + string origin = (double)gpsRealTime.Longitude + "," + (double)gpsRealTime.Latitude; + string destination = (double)order.Longitude + "," + (double)order.Latitude; + var pathPlanningModel = MapHelper.GetPathPlanningByDriving(origin, destination); + if (pathPlanningModel.status == "1" && pathPlanningModel.info == "OK") + { + order.Distance = $"{ Convert.ToDouble(pathPlanningModel.route.paths[0].distance) / 1000}KM"; + order.ExpectArriveDate = DateTimeHelper.ToChineseDate(Convert.ToInt32(pathPlanningModel.route.paths[0].duration)); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"GetMapMonitorAsync:{ex.StackTrace}"); + } + + + } + } + + var adminOrderListOutput = new AdminOrderListOutput + { + PagedList = new PagedList + { + Items = orders, + TotalCount = orders.Count + }, + StayAssignCount = allOrders.Count(x => x.Status == (int)OrderStatus.StayAssign), + AssignCount = allOrders.Count(x => new int[] { (int)OrderStatus.Assign, (int)OrderStatus.Receive, (int)OrderStatus.Travel, (int)OrderStatus.Appear }.Contains(x.Status)), + CompleteCount = allOrders.Count(x => new int[] { (int)OrderStatus.Complete, (int)OrderStatus.Sign, (int)OrderStatus.Leave, (int)OrderStatus.ArriveHome }.Contains(x.Status)), + EvaluateCount = allOrders.Count(x => x.Status == (int)OrderStatus.Evaluate) + }; + return adminOrderListOutput; + } + + + + /// + /// 保存待指派 + /// + /// + /// + [HttpPost] + [Route("api/v1/order/stayassign")] + public async Task StayAssignAsync(StayAssignInput stayAssign) + { + var order = await _repository.FindOrDefaultAsync(stayAssign.Id); + long constructionId = 0; + long projectId = stayAssign.ProjectId; + if (order.IsNotNull()) + { + + //工程名称是否存在,不存在新增,返回工程信息 + if (stayAssign.ProjectId == 0) + { + projectId = await GetProjectId(stayAssign.Latitude, stayAssign.Longitude, stayAssign.Address, stayAssign.ProjectName); + } + + constructionId = stayAssign.ConstructionId; + //施工单位是否存在,不存在新增,返回工程信息 + if (stayAssign.ConstructionName.IsNotEmptyOrNull()) + { + constructionId = await GetConstructionId(stayAssign.ConstructionId, stayAssign.ConstructionName); + } + + order.ProjectId = projectId; + order.ProjectName = stayAssign.ProjectName; + order.ArriveDate = stayAssign.ArriveDate; + order.Longitude = stayAssign.Longitude; + order.Latitude = stayAssign.Latitude; + order.Address = stayAssign.Address; + order.ConstructionId = constructionId; + order.VehicleType = stayAssign.VehicleType; + order.OrderContent = HtmlHelper.ReplaceHtmlMark(stayAssign.OrderContent); + order.VehicleCode = ""; + order.OrderVehiclePerson = ""; + await _repository.UpdateNowAsync(order); + } + else + { + order = stayAssign.Adapt(); + //工程名称是否存在,不存在新增,返回工程信息 + if (stayAssign.ProjectId == 0) + { + projectId = await GetProjectId(stayAssign.Latitude, stayAssign.Longitude, stayAssign.Address, stayAssign.ProjectName); + } + + constructionId = stayAssign.ConstructionId; + //施工单位是否存在,不存在新增,返回工程信息 + if (stayAssign.ConstructionName.IsNotEmptyOrNull()) + { + constructionId = await GetConstructionId(stayAssign.ConstructionId, stayAssign.ConstructionName); + } + order.CompanyId = _userManager.CompanyId; + order.Status = (int)OrderStatus.StayAssign; + order.OrderSource = (int)OrderSourceEnum.Input; + order.ArriveDate = stayAssign.ArriveDate; + order.ConstructionId = constructionId; + order.OrderContent = HtmlHelper.ReplaceHtmlMark(stayAssign.OrderContent); + order.Address = stayAssign.Address.IsNull() ? "" : stayAssign.Address; + order.ProjectId = projectId; + order.VehicleCode = ""; + order.OrderVehiclePerson = ""; + var orderId = (await _repository.InsertNowAsync(order)).Entity.Id; + if (orderId <= 0) + { + throw Oops.Bah($"任务保存失败"); + } + } + await InsertProjectPersonAsync(stayAssign.OrderContent, projectId, constructionId); + await UpdateProjectAddressAsync(projectId, stayAssign.Latitude, stayAssign.Longitude, stayAssign.Address); + } + + + + + /// + /// 指派订单 + /// + /// + /// + [HttpPost] + [UnitOfWork] + [Route("api/v1/order/assign")] + public async Task AssignAsync(AssignOrderInput assign) + { + + var order = await _repository.FindOrDefaultAsync(assign.Id); + long constructionId = 0; + //是否更改工程 + bool isChangeProject = false; + //施工更改订单内容 + bool isChangeOrderContent = false; + //是否更改到场时间 + bool isChangeArrive = false; + //是否更改任务车型 + bool isChangeVehicleType = false; + //是否更改施工地点 + bool isChangeAddress = false; + //是否更改指派车辆 + bool isChangeVehicle = false; + //是否更改人员 + bool isChangePersonnel = false; + + bool isChange = false; + + #region order + + long projectId = assign.ProjectId; + //工程名称是否存在,不存在新增,返回工程信息 + if (assign.ProjectId == 0) + { + projectId = await GetProjectId(assign.Latitude, assign.Longitude, assign.Address, assign.ProjectName); + } + constructionId = assign.ConstructionId; + //施工单位是否存在,不存在新增,返回工程信息 + if (assign.ConstructionName.IsNotEmptyOrNull()) + { + constructionId = await GetConstructionId(assign.ConstructionId, assign.ConstructionName); + } + //未保存直接指派 + if (order.IsNull()) + { + var entity = new Order(); + entity = assign.Adapt(); + entity.Status = (int)OrderStatus.Assign; + entity.CompanyId = _userManager.CompanyId; + entity.OrderSource = (int)OrderSourceEnum.Input; + entity.AssignDate = DateTime.Now; + entity.AssignUserId = _userManager.UserId; + entity.VehicleId = assign.VehicleId; + entity.VehicleCode = assign.VehicleCode; + entity.IsOutside = assign.IsOutside; + entity.VehicleType = assign.VehicleType; + entity.OrderContent = HtmlHelper.ReplaceHtmlMark(assign.OrderContent); + entity.ConstructionId = constructionId; + entity.ProjectId = projectId; + entity.VehicleCode = assign.VehicleCode; + entity.OrderVehiclePerson = assign.OrderVehiclePerson; + order = (await _repository.InsertNowAsync(entity)).Entity; + if (order.Id <= 0) + { + throw Oops.Bah($"指派失败"); + } + + var orderContent = assign.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark((assign.OrderContent.Substring(0, 45))) + "..." : HtmlHelper.ReplaceHtmlMark(assign.OrderContent) + "..."; + if (assign.IsOutside) + { + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == assign.VehicleId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotEmptyOrNull()) + { + var company = await _companyRepository.Where(x => x.Id == _userManager.CompanyId).FirstOrDefaultAsync(); + var user = await _userRepository.Where(x => x.Id == _userManager.UserId).FirstOrDefaultAsync(); + //消息推送 + var data = new WeixinTemplate_AssignOrder("同行叫车通知", assign.ProjectName, "同行叫车", orderContent, assign.ArriveDate.ToString("yyyy-MM-dd HH:mm:ss"), $"{company.CompanyName}公司请车,请点击接单并准时出车,谢谢!"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver=false&type=1&isOutSide=true"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"未保存直接指派{JsonConvert.SerializeObject(result)}"); + } + } + else + { + + var orderVehicles = assign.OrderVehicles.Adapt>(); + + foreach (var oVehicle in orderVehicles) + { + var orderVehicle = (await _orderVehicleRepository.InsertNowAsync(oVehicle)).Entity; + if (orderVehicle.Id > 0) + { + orderVehicle.OrderId = order.Id; + await _orderVehicleRepository.UpdateNowAsync(orderVehicle); + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == orderVehicle.UserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotEmptyOrNull()) + { + //消息推送 + var data = new WeixinTemplate_AssignOrder("出车任务通知", assign.ProjectName, "出车任务", HtmlHelper.ReplaceHtmlTag(orderContent), assign.ArriveDate.ToString("yyyy-MM-dd HH:mm:ss"), "请点击接单并准时出车"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver={orderVehicle.IsDriver.ToString().ToLower()}&type=1"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"保存直接指派{JsonConvert.SerializeObject(result)}"); + + } + + } + } + } + } + //保存后指派 + else + { + + var orderContent = HtmlHelper.ReplaceHtmlMark(assign.OrderContent); + //定义消息通知message + string message = ""; + if (order.ProjectId != assign.ProjectId && order.ProjectId > 0) + { + isChangeProject = true; + isChange = true; + message += "[项目名称]"; + } + if (order.ArriveDate != assign.ArriveDate) + { + isChangeArrive = true; + isChange = true; + message += "[到场时间]"; + } + if (order.OrderContent != orderContent) + { + isChangeOrderContent = true; + isChange = true; + message += "[任务内容]"; + + } + if (order.VehicleType != assign.VehicleType && order.VehicleType > 0) + { + isChangeVehicleType = true; + isChange = true; + message += "[任务车型]"; + + } + if (order.Address != assign.Address) + { + isChangeAddress = true; + isChange = true; + message += "[施工地点]"; + + } + if (order.VehicleId != assign.VehicleId && order.VehicleId>0) + { + isChangeVehicle = true; + isChange = true; + message += "[出车车辆]"; + + } + if (order.Status <= 20) + { + order.Status = (int)OrderStatus.Assign; + } + order.ProjectId = assign.ProjectId; + order.ProjectName = assign.ProjectName; + order.AssignDate = DateTime.Now; + order.Latitude = assign.Latitude; + order.Longitude = assign.Longitude; + order.Address = assign.Address; + order.OrderContent = orderContent; + order.CompanyId = _userManager.CompanyId; + order.OrderSource = (int)OrderSourceEnum.Input; + order.AssignUserId = _userManager.UserId; + order.VehicleId = assign.VehicleId; + order.VehicleCode = assign.VehicleCode; + order.IsOutside = assign.IsOutside; + order.VehicleType = assign.VehicleType; + order.OrderVehiclePerson = assign.OrderVehiclePerson; + order.ArriveDate = assign.ArriveDate; + order.ConstructionId = constructionId; + order.ProjectId = projectId; + await _repository.UpdateNowAsync(order); + var newOrderVehicles = assign.OrderVehicles.Adapt>(); + var oldOrderVehicles = _orderVehicleRepository.Where(x => x.OrderId == order.Id).ToList(); + orderContent = assign.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark(assign.OrderContent.Substring(0, 45)) + "..." : HtmlHelper.ReplaceHtmlMark(assign.OrderContent) + "..."; + + if (order.IsOutside) + { + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == assign.VehicleId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotEmptyOrNull()) + { + var company = await _companyRepository.Where(x => x.Id == _userManager.CompanyId).FirstOrDefaultAsync(); + var user = await _userRepository.Where(x => x.Id == _userManager.UserId).FirstOrDefaultAsync(); + //消息推送 + var data = new WeixinTemplate_AssignOrder("同行叫车通知", assign.ProjectName, "同行叫车", orderContent, assign.ArriveDate.ToString("yyyy-MM-dd HH:mm:ss"), $"{company.CompanyName}公司请车,请点击接单并准时出车,谢谢!"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver=false&type=1&isOutSide=true"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"未保存直接指派{JsonConvert.SerializeObject(result)}"); + } + } + + //需撤销的list + var revokeOldOrderVehicles = oldOrderVehicles.Except(newOrderVehicles, new OrderVehicleCompara()).ToList(); + //是否替换司机 + isChangePersonnel= revokeOldOrderVehicles.Any(x => x.IsDriver); + foreach (var revokeOldOrderVehicle in revokeOldOrderVehicles) + { + + await _orderVehicleRepository.DeleteNowAsync(revokeOldOrderVehicle); + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == revokeOldOrderVehicle.UserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("出车任务撤销通知", order.ProjectName, "出车撤销", orderContent, order.ArriveDate.ToString("yyyy-MM-dd HH:mm:ss"), "您的出车任务已被取消,请点击查看"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver={revokeOldOrderVehicle.IsDriver.ToString().ToLower()}&type=1"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"出车任务撤销通知{JsonConvert.SerializeObject(result)}"); + + } + + } + + //需新增的list + var newlyOrderVehicles = newOrderVehicles.Except(oldOrderVehicles, new OrderVehicleCompara()).ToList(); + foreach (var newlyOrderVehicle in newlyOrderVehicles) + { + var newVehicleId = (await _orderVehicleRepository.InsertNowAsync(newlyOrderVehicle)).Entity.Id; + if (newVehicleId > 0) + { + newlyOrderVehicle.OrderId = order.Id; + await _orderVehicleRepository.UpdateNowAsync(newlyOrderVehicle); + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == newlyOrderVehicle.UserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotEmptyOrNull()) + { + ////消息推送 + var data = new WeixinTemplate_AssignOrder("出车任务通知", order.ProjectName, "出车任务", orderContent, order.ArriveDate.ToString("yyyy-MM-dd HH:mm:ss"), "请点击接单并准时出车"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver={newlyOrderVehicle.IsDriver.ToString().ToLower()}&type=1"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"出车任务通知{JsonConvert.SerializeObject(result)}"); + // isChangePersonnel = true; + + } + + } + } + + //更改出车人员变更任务状态 + if (isChangePersonnel) + { + await "update dc_order set Status=20,ReceiveDate=null where id=@id".SqlNonQueryAsync(new { id = order.Id }); + } + string message2 = message; + if (isChange) + { + var orderVehicles = _orderVehicleRepository.Where(x => x.OrderId == order.Id).ToList(); + foreach (var orderVehicle in orderVehicles) + { + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == orderVehicle.UserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotEmptyOrNull()) + { + var data = new WeixinTemplate_AssignOrder($"出车任务变更通知", order.ProjectName, "出车任务变更", orderContent, order.ArriveDate.ToString("yyyy-MM-dd HH:mm:ss"), message += "有调整,请点击查看并相互告知"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver={orderVehicle.IsDriver.ToString().ToLower()}&type=1"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + } + } + await _cacheService.SetOrderReadAsync(order.Id, message2); + }; + } + { + //新增工地联系人 + await InsertProjectPersonAsync(assign.OrderContent, projectId, constructionId); + await UpdateProjectAddressAsync(projectId, assign.Latitude, assign.Longitude, assign.Address); + + //同步车组人员 + if (assign.IsReplaceOrderVehicle) + { + var orderVehicles = await _orderVehicleRepository.Where(x => x.OrderId == order.Id).ToListAsync(); + await _vehiclePersonitory.Context.DeleteRangeAsync(b => b.VehicleId == order.VehicleId); ; + foreach (var orderVehicle in orderVehicles) + { + var vehiclePerson = new VehiclePerson() + { + VehicleId = order.VehicleId, + UserId = orderVehicle.UserId, + UserName = orderVehicle.UserName, + UserPhone = orderVehicle.UserPhone, + IsDriver = orderVehicle.IsDriver + + }; + await _vehiclePersonitory.InsertNowAsync(vehiclePerson); + } + await _cacheService.RemoveVehiclePersonAsync(order.VehicleId); + } + } + + #endregion + } + + + + + /// + /// 完成订单 + /// + /// + /// + [HttpGet] + [Route("api/v1/order/complete/{orderId}")] + public async Task CompleteAsync(long orderId) + { + var order = await _repository.FindOrDefaultAsync(orderId); + if (order.IsNotNull()) + { + var orderContent = order.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark(order.OrderContent.Substring(0, 45)) + "..." : HtmlHelper.ReplaceHtmlMark(order.OrderContent) + "..."; + + if (_userManager.SuperAdmin) + { + order.CompleteDate = DateTime.Now; + order.Status = (int)OrderStatus.Complete; + await _repository.UpdateNowAsync(order); + + //推送至所有车组人员已完工通知 + var orderVehicles = _orderVehicleRepository.Where(x => x.OrderId == order.Id).ToList(); + if (orderVehicles.IsNotNull() && orderVehicles.Count > 0) + { + foreach (var orderVehicle in orderVehicles) + { + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == orderVehicle.UserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("已完工通知", order.ProjectName, "已完工", orderContent, order.ArriveDate.ToString("yyyy-MM-dd HH:mm:ss"), "恭喜任务已完成!返回时记得交单哦,辛苦 了~"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver={orderVehicle.IsDriver.ToString().ToLower()}&type=1"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"已完工通知{JsonConvert.SerializeObject(result)}"); + } + } + } + { + //推送至派单人 + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == order.AssignUserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("已完工通知", order.ProjectName, "已完工", orderContent, order.ArriveDate.ToString("yyyy-MM-dd HH:mm:ss"), "恭喜任务已完成!返回时记得交单哦,辛苦 了~"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver=false&type=2"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"已完工通知{JsonConvert.SerializeObject(result)}"); + } + } + + } + else + { + throw Oops.Bah("暂无权限"); + } + } + else + { + throw Oops.Bah("订单不存在"); + } + } + + + /// + /// 删除订单 + /// + /// + /// + [HttpDelete] + [Route("api/v1/order/{orderId}")] + public async Task DeleteAsync(long orderId) + { + var order = await _repository.FindOrDefaultAsync(orderId); + if (order.IsNotNull()) + { + if (_userManager.SuperAdmin) + { + order.IsDeleted = true; + await _repository.UpdateNowAsync(order); + } + else + { + throw Oops.Bah("暂无权限"); + } + } + else + { + throw Oops.Bah("订单不存在"); + } + } + + + /// + /// 撤销订单 + /// + /// + /// + [HttpPut] + [Route("api/v1/cancel/order/{orderId}")] + public async Task CancelAsync(long orderId) + { + var order = await _repository.FindOrDefaultAsync(orderId); + if (order.IsNotNull()) + { + var orderContent = order.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark(order.OrderContent.Substring(0, 45)) + "..." : HtmlHelper.ReplaceHtmlMark(order.OrderContent) + "..."; + + if (_userManager.SuperAdmin) + { + order.Status = (int)OrderStatus.Cancel; + await _repository.UpdateNowAsync(order); + + //推送至所有车组人员已完工通知 + var orderVehicles = _orderVehicleRepository.Where(x => x.OrderId == order.Id).ToList(); + if (orderVehicles.IsNotNull() && orderVehicles.Count > 0) + { + foreach (var orderVehicle in orderVehicles) + { + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == orderVehicle.UserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("出车任务撤销通知", order.ProjectName, "出车任务撤销", orderContent, order.ArriveDate.ToString("yyyy-MM-dd HH:mm:ss"), "出车任务已撤销,请悉知并抓紧时间返回!"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver={orderVehicle.IsDriver.ToString().ToLower()}&type=1"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"出车任务撤销通知{JsonConvert.SerializeObject(result)}"); + + } + } + } + } + else + { + throw Oops.Bah("暂无权限"); + } + } + else + { + throw Oops.Bah("订单不存在"); + } + } + + + + #endregion + + #region 司机端 + + /// + /// 接单 + /// + /// + /// + [HttpGet] + [Route("api/v1/order/receive/{orderId}")] + public async Task ReceiveAsync(long orderId) + { + var order = await _repository.FindOrDefaultAsync(orderId); + if (order.IsNotNull()) + { + var orderContent = order.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark(order.OrderContent.Substring(0, 45)) + "..." : HtmlHelper.ReplaceHtmlMark(order.OrderContent) + "..."; + var isDriver = _orderVehicleRepository.Any(x => x.OrderId == orderId && x.IsDriver == true && x.UserId == _userManager.UserId); + if (isDriver) + { + order.ReceiveDate = DateTime.Now; + order.Status = (int)OrderStatus.Receive; + //存储当前定位信息 + var vehicleGps = await _gpsRealTimeRepository.GetGpsRealTimeByVehicleId(order.VehicleId); + if (vehicleGps.IsNotNull()) + { + dynamic clay = Clay.Object(new + { + Latitude = vehicleGps.Latitude, + Longitude = vehicleGps.Longitude + }); + await _cacheService.SetVehicleGpsAsync(orderId, clay); + } + await _repository.UpdateNowAsync(order); + //推送完工提交签证单通知给司机 + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == _userManager.UserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("完工提交签证单通知", order.ProjectName, "完工提交签证单", orderContent, order.ArriveDate.ToString("yyyy -MM-dd HH:mm:ss"), "完工后请点击这里,拍照回传签证单!"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver=true&type=1"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"完工提交签证单通知{JsonConvert.SerializeObject(result)}"); + + } + //v1.2.7 推送至派单调度以及管理员 + { + //管理员 + var adminUserIds = await _employeeRepository.DetachedEntities.Where(x => x.CompanyId == _userManager.CompanyId && x.RoleId == (int)RoleStatusEnum.Administrator && x.Status == 1 && !x.IsDeleted).Select(x => x.UserId).ToListAsync(); + //派单人 + adminUserIds.Add(order.AssignUserId); + //获取订单所有车组人员信息 + var orderVehicles = await _orderVehicleRepository.DetachedEntities.Where(x => x.OrderId == order.Id).ToListAsync(); + var orderVehicleDriverName = orderVehicles.FirstOrDefault(x => x.IsDriver).UserName; + var orderVehicleCrewsName = string.Join(",", orderVehicles.Where(x => !x.IsDriver).Select(x => x.UserName).ToList()); + foreach (var adminUserId in adminUserIds) + { + var wxAdminUser = _wxUserRelationRepository.Where(x => x.UserId == adminUserId).FirstOrDefault(); + if (wxAdminUser.IsNotNull() && wxAdminUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("已接单提醒", order.ProjectName, "出车任务", orderContent, order.ArriveDate.ToString("yyyy -MM-dd HH:mm:ss"), $"[{order.VehicleCode}]号车,{orderVehicleDriverName}已接单,{orderVehicleCrewsName}已阅读"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver=false&type=2"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxAdminUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"已接单提醒{JsonConvert.SerializeObject(result)}"); + } + } + } + //v1.2.8推送变更提醒 + { + var message = await _cacheService.GetOrderReadAsync(order.Id); + if (message.IsNotEmptyOrNull()) + { + //管理员 + var adminUserIds = await _employeeRepository.DetachedEntities.Where(x => x.CompanyId == _userManager.CompanyId && x.RoleId == (int)RoleStatusEnum.Administrator && x.Status == 1 && !x.IsDeleted).Select(x => x.UserId).ToListAsync(); + //派单人 + adminUserIds.Add(order.AssignUserId); + //业务员 + if (order.SalesmanId > 0) adminUserIds.Add(order.SalesmanId); + //获取订单所有车组人员信息 + var orderVehicles = await _orderVehicleRepository.DetachedEntities.Where(x => x.OrderId == order.Id).ToListAsync(); + var orderVehicleDriverName = orderVehicles.FirstOrDefault(x => x.IsDriver).UserName; + var orderVehicleCrewsName = string.Join(",", orderVehicles.Where(x => !x.IsDriver).Select(x => x.UserName).ToList()); + foreach (var adminUserId in adminUserIds) + { + var wxAdminUser = _wxUserRelationRepository.Where(x => x.UserId == adminUserId).FirstOrDefault(); + if (wxAdminUser.IsNotNull() && wxAdminUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("已接单提醒", order.ProjectName, "出车任务", orderContent, order.ArriveDate.ToString("yyyy -MM-dd HH:mm:ss"), $"{message}变更通知,[{order.VehicleCode}]车,{orderVehicleDriverName},{orderVehicleCrewsName}已收到已查看"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver=false&type=2"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxAdminUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"已接单提醒{JsonConvert.SerializeObject(result)}"); + } + } + await _cacheService.RemoveOrderReadAsync(order.Id); + + } + } + } + else + { + throw Oops.Bah("暂无权限"); + } + } + else + { + throw Oops.Bah("订单不存在"); + } + } + + /// + /// 签单 + /// + /// + /// + [HttpPost] + [UnitOfWork] + [Route("api/v1/order/sign")] + public async Task SignAsync(SignInput sign) + { + + var order = await _repository.FindOrDefaultAsync(sign.OrderId); + if (order.IsNotNull()) + { + var orderContent = order.OrderContent.Length > 45 ? HtmlHelper.ReplaceHtmlMark(order.OrderContent.Substring(0, 45)) + "..." : HtmlHelper.ReplaceHtmlMark(order.OrderContent) + "..."; + + var isDriver = _orderVehicleRepository.Any(x => x.OrderId == sign.OrderId && x.IsDriver == true); + if (isDriver) + { + order.SignDate = DateTime.Now; + order.Status = (int)OrderStatus.Sign; + await _repository.UpdateNowAsync(order); + //推送通知 + var ordervisa = await _orderVisaRepository.Where(x => x.OrderId == sign.OrderId).FirstOrDefaultAsync(); + if (ordervisa.IsNotNull()) + { + await _orderVisaRepository.DeleteNowAsync(ordervisa); + } + var orderVisaId = (await _orderVisaRepository.InsertNowAsync(new OrderVisa() + { + OrderId = sign.OrderId, + Picture = sign.Picture, + })).Entity.Id; + + if (orderVisaId <= 0) + { + throw Oops.Bah("签单失败"); + } + //推送至所有车组人员已完工通知 + var orderVehicles = _orderVehicleRepository.Where(x => x.OrderId == order.Id).ToList(); + if (orderVehicles.IsNotNull() && orderVehicles.Count > 0) + { + foreach (var orderVehicle in orderVehicles) + { + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == orderVehicle.UserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("已完工通知", order.ProjectName, "已完工", orderContent, order.ArriveDate.ToString("yyyy -MM-dd HH:mm:ss"), "恭喜任务已完成!返回时记得交单哦,辛苦了~"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver={orderVehicle.IsDriver.ToString().ToLower()}&type=1"; + var result = await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + Console.WriteLine($"已完工通知{JsonConvert.SerializeObject(result)}"); + + } + } + } + { + //推送至派单人 + var wxUser = _wxUserRelationRepository.Where(x => x.UserId == order.AssignUserId).FirstOrDefault(); + if (wxUser.IsNotNull() && wxUser.WxOfficialOpenId.IsNotNull()) + { + var data = new WeixinTemplate_AssignOrder("已完工通知", order.ProjectName, "已完工", orderContent, order.ArriveDate.ToString("yyyy -MM-dd HH:mm:ss"), "恭喜任务已完成!返回时记得交单哦,辛苦了~"); + TemplateModel_MiniProgram miniProgram = new TemplateModel_MiniProgram(); + miniProgram.appid = _weixinSettingOptions.WxOpenAppId; + miniProgram.pagepath = $"pages/taskInfo/taskInfo?id={order.Id}&isDriver=false&type=2"; + await TemplateApi.SendTemplateMessageAsync(_weixinSettingOptions.WeixinAppId, wxUser.WxOfficialOpenId, data.TemplateId, "pages/index/index", data, miniProgram); + Console.WriteLine($"{miniProgram.pagepath}"); + } + } + } + else + { + throw Oops.Bah("暂无权限"); + } + } + else + { + throw Oops.Bah("订单不存在"); + } + } + + + + + + + /// + /// 车组人员端任务列表 + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/driver/orders/search")] + public async Task> DriverPageAsync(int currentPage = 1, int pageSize = 10) + { + var orders = await (from ov in _orderVehicleRepository.Where(x => x.UserId == _userManager.UserId && x.IsDeleted == false).AsQueryable() + join o in _repository.Where(x => x.CompanyId == _userManager.CompanyId && x.IsDeleted == false && x.Status != (int)OrderStatus.Cancel).AsQueryable() on ov.OrderId equals o.Id + select new OrderVehicleListOutput + { + Id = ov.OrderId, + OrderContent = o.OrderContent, + Status = o.Status, + VehicleCode = o.VehicleCode, + OrderVehiclePerson = o.OrderVehiclePerson, + IsDriver = ov.IsDriver, + CreatedTime = o.CreatedTime + }) + .OrderByDescending(x => x.CreatedTime) + // .OrderBy(x => x.Status) + .ToPagedListAsync(currentPage, pageSize); + + + foreach (var order in orders.Items) + { + order.OrderContent = HtmlHelper.ReplaceHtmlMark(order.OrderContent); + order.StatusName = typeof(OrderStatus).GetDescription(order.Status); + if (new int[] { (int)OrderStatus.Assign }.Contains(order.Status)) + { + order.StatusName = "新任务"; + } + if (new int[] { (int)OrderStatus.Receive, (int)OrderStatus.Travel, (int)OrderStatus.Appear }.Contains(order.Status)) + { + order.StatusName = "已接单"; + } + if (new int[] { (int)OrderStatus.Complete, (int)OrderStatus.Sign, (int)OrderStatus.Leave, (int)OrderStatus.Evaluate, (int)OrderStatus.ArriveHome }.Contains(order.Status)) + { + order.StatusName = "已完工"; + } + } + + return orders; + } + #endregion + + #region 外租伙伴 + + /// + /// 外租伙伴端任务列表 + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/train/orders/search")] + public async Task> TrainPageAsync(int currentPage = 1, int pageSize = 10) + { + //公司内部派单 + var orders = await (from o in _repository.Where(x => x.VehicleId == _userManager.UserId && x.IsOutside == true && x.IsDeleted == false).AsQueryable() + select new OrderVehicleListOutput + { + Id = o.Id, + OrderContent = o.OrderContent, + Status = o.Status, + VehicleCode = o.VehicleCode, + OrderVehiclePerson = o.OrderVehiclePerson, + IsDriver = false, + CreatedTime = o.CreatedTime + }) + .OrderByDescending(x => x.CreatedTime) + .ToPagedListAsync(currentPage, pageSize); + + foreach (var order in orders.Items) + { + order.OrderContent = HtmlHelper.ReplaceHtmlMark(order.OrderContent); + } + return orders; + } + + #endregion + + #region 公共方法 + + /// + /// 查询订单明细 + /// + /// + /// + [HttpGet] + [Route("api/v1/order/{id}")] + [AllowAnonymous] + public async Task GetByIdAsync(long id) + { + var order = await _repository.FindOrDefaultAsync(id); + if (order.IsNotNull()) + { + //如果订单状态未接单,且权限为车组人员,且指派为司机 + if (_userManager.RoleId == (int)RoleStatusEnum.CrewMembers && order.Status == (int)OrderStatus.Assign) + { + var isAnyAsync = await _orderVehicleRepository.AnyAsync(x => x.OrderId == id && x.IsDriver && x.UserId == _userManager.UserId); + if (isAnyAsync) + { + + await ReceiveAsync(id); + } + + } + + var orderOutput = new OrderOutput(); + orderOutput.Id = order.Id; + orderOutput.ProjectId = order.ProjectId; + orderOutput.ProjectName = order.ProjectName; + orderOutput.ConstructionId = order.ConstructionId; + orderOutput.ConstructionName = (await _constructionRpository.FirstOrDefaultAsync(x => x.Id == order.ConstructionId))?.ConstructionName; + orderOutput.SalesmanId = order.SalesmanId; + orderOutput.VehicleId = order.VehicleId; + orderOutput.VehicleCode = order.VehicleCode; + orderOutput.Status = order.Status; + orderOutput.StatusName = typeof(OrderStatus).GetDescription(order.Status); + orderOutput.ArriveDate = order.ArriveDate; + if (order.ProjectName.IsNotEmptyOrNull()) + { + orderOutput.OrderTitle = order.ProjectName; + } + else + { + orderOutput.OrderTitle = order.OrderContent.Length >= 13 ? order.OrderContent.Substring(0, 13).Trim().ToString() : order.OrderContent.Trim(); + } + orderOutput.OrderContent = order.OrderContent; + orderOutput.OrderSource = order.OrderSource; + orderOutput.OrderSourceName = typeof(OrderSourceEnum).GetDescription(order.OrderSource); + orderOutput.OrderVehiclePerson = order.OrderVehiclePerson; + orderOutput.Latitude = order.Latitude; + orderOutput.Longitude = order.Longitude; + orderOutput.Address = order.Address; + orderOutput.IsOutside = order.IsOutside; + #region OrderStatusDates + Dictionary orderStatusDate = new Dictionary(); + if (_userManager.SuperAdmin) + { + orderStatusDate.Add("派单", order.AssignDate.IsNull() ? "" : order.AssignDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + orderStatusDate.Add("接单", order.ReceiveDate.IsNull() ? "" : order.ReceiveDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + orderStatusDate.Add("出发", order.TravelDate.IsNull() ? "" : order.TravelDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + orderStatusDate.Add("到达", order.AppearDate.IsNull() ? "" : order.AppearDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + orderStatusDate.Add("完工", order.CompleteDate.IsNull() ? "" : order.CompleteDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + orderStatusDate.Add("签单", order.SignDate.IsNull() ? "" : order.SignDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + orderStatusDate.Add("离开", order.LeaveDate.IsNull() ? "" : order.LeaveDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + orderStatusDate.Add("评价", order.EvaluateDate.IsNull() ? "" : order.EvaluateDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + orderStatusDate.Add("到家", order.ArriveHomeDate.IsNull() ? "" : order.ArriveHomeDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + } + else + { + orderStatusDate.Add("派单", order.AssignDate.IsNull() ? "" : order.AssignDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + if (order.Status == (int)OrderStatus.Receive) + { + orderStatusDate.Add("接单", order.ReceiveDate.IsNull() ? "" : order.ReceiveDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + } + orderStatusDate.Add("签单", order.SignDate.IsNull() ? "" : order.SignDate.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss")); + } + orderOutput.OrderStatusDates = orderStatusDate.ToList(); + #endregion + + orderOutput.VehicleType = order.VehicleType; + orderOutput.VehicleTypeName = _vehicleTypeRepository.Where(x => x.Id == order.VehicleType).FirstOrDefault()?.Name; + + + if (order.IsOutside) + { + var user = await _userRepository.Where(x => x.Id == order.VehicleId).FirstOrDefaultAsync(); + var orderVehicles = new List(); + if (user.IsNotNull()) + { + orderVehicles.Add(new OrderVehicleOutput() + { + UserId = user.Id, + UserName = user.UserName, + UserPhone = user.Phone, + IsDriver = false + }); + } + orderOutput.OrderVehicles = orderVehicles; + } + else + { + var orderVehicles = await _orderVehicleRepository.Where(x => x.OrderId == order.Id).ToListAsync(); + if (orderVehicles.IsNotNull() && orderVehicles.Count > 0) + { + orderOutput.OrderVehicles = orderVehicles.Adapt>(); + } + } + + //签证单 + var orderVisas = _orderVisaRepository.Where(x => x.OrderId == order.Id).ToList(); + if (orderVisas.Count > 0) + { + orderOutput.OrderVisas = orderVisas.Adapt>(); + } + orderOutput.Distance = ""; + orderOutput.ExpectArriveDate = ""; + //查询当前车辆是否有任务 + try + { + if (new long[] { (long)OrderStatus.Receive, (long)OrderStatus.Travel }.Contains(order.Status)) + { + //车辆Gps + var gpsRealTime = await _gpsRealTimeRepository.GetGpsRealTimeByVehicleId(order.VehicleId); + string origin = (double)gpsRealTime.Longitude + "," + (double)gpsRealTime.Latitude; + string destination = (double)order.Longitude + "," + (double)order.Latitude; + var pathPlanningModel = MapHelper.GetPathPlanningByDriving(origin, destination); + if (pathPlanningModel.status == "1" && pathPlanningModel.info == "OK") + { + orderOutput.Distance = $"{ Convert.ToDouble(pathPlanningModel.route.paths[0].distance) / 1000}KM"; + orderOutput.ExpectArriveDate = DateTimeHelper.ToChineseDate(Convert.ToInt32(pathPlanningModel.route.paths[0].duration)); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"GetPathPlanningByDriving:{ex.Message}"); + } + + return orderOutput; + } + else + { + + throw Oops.Bah("该任务不存在"); + } + + } + + + + + /// + /// v1.2.2 工地联系人调整为非必填项,如果用户先录入 了工程名称基础数据,而且工程名称派工开关 设置为打开,而且用户派工时选择了工程名称 的情况下,则用户录入派工任务保存或指派成 功后,自动将任务内容里该工地联系人关联至 该工程的工地联系人这里 + /// + /// + /// + /// + /// + private async Task InsertProjectPersonAsync(string orderContent, long projectId, long constructionId) + { + string[] phones = RegexHelper.ReturnPhones(orderContent); + if (phones.Length > 0) + { + foreach (var phone in phones) + { + var userId = await _employeeService.AddAsync(new EmployeeAddInput() + { + EmployeeName = "工地联系人", + EmployeePhone = phone.Trim(), + RoleId = (int)RoleStatusEnum.ProjectPerson, + RoleName = typeof(RoleStatusEnum).GetDescription((int)RoleStatusEnum.ProjectPerson) + }); + + if (projectId > 0) + { + var projectPerson = await _projectPersonRepository.FirstOrDefaultAsync(x => x.ProjectId == projectId && x.ProjectPersonPhone == phone); + if (projectPerson.IsNull()) + { + ProjectPerson person = new ProjectPerson(); + person.ProjectId = projectId; + person.ProjectPersonId = userId; + person.ProjectPersonName = "工地联系人"; + person.ProjectPersonPhone = phone; + await _projectPersonRepository.InsertNowAsync(person); + + } + + + var project = await _projectRepository.FirstOrDefaultAsync(x => x.Id == projectId); + if (project.IsNotNull()) + { + var construction = await _constructionRpository.FirstOrDefaultAsync(x => x.Id == constructionId); + if (constructionId > 0) + { + project.ConstructionId = constructionId; + project.ConstructionName = construction.ConstructionName; + await _projectRepository.UpdateNowAsync(project); + } + + } + await _cacheService.RemoveProjectAsync(projectId); + await _cacheService.RemoveProjectListAsync(projectId); + } + } + + } + } + + + #region v1.2.7 更新回执 + /// + /// 更新签证单 + /// + /// + /// + [HttpPut] + [Route("api/v1/ordervisa")] + public async Task OrderVisaAsync(SignInput sign) + { + + var order = await _repository.FindOrDefaultAsync(sign.OrderId); + if (order.IsNotNull()) + { + + var isDriver = _orderVehicleRepository.Any(x => x.OrderId == sign.OrderId && x.IsDriver == true); + if (isDriver || _userManager.SuperAdmin) + { + var ordervisa = await _orderVisaRepository.Where(x => x.OrderId == sign.OrderId).FirstOrDefaultAsync(); + if (ordervisa.IsNotNull()) + { + await _orderVisaRepository.DeleteNowAsync(ordervisa.Id); + } + var orderVisaId = (await _orderVisaRepository.InsertNowAsync(new OrderVisa() + { + OrderId = sign.OrderId, + Picture = sign.Picture, + })).Entity.Id; + + if (orderVisaId <= 0) + { + throw Oops.Bah("更新回执失败"); + } + } + else + { + throw Oops.Bah("暂无权限"); + } + } + else + { + throw Oops.Bah("订单不存在"); + } + } + #endregion + + #endregion + + #region 回单查询 + + /// + /// 回单查询列表 + /// + /// 0全部,1未接单,2已结单,3已完成,4已评价 + /// + /// + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/receipt/orders/search")] + public async Task> ReceiptPageAsync(DateTime startTime, DateTime endTime, int status = 0, int currentPage = 1, int pageSize = 10, string key = "") + { + var orders = await _repository.DetachedEntities + .WhereIf(new long[] { (long)RoleStatusEnum.Salesman, (long)RoleStatusEnum.PartTimeSalesman }.Contains(_userManager.RoleId), + x => x.CreatedUserId == _userManager.UserId || x.SalesmanId == _userManager.UserId) + .Where(x => x.CompanyId == _userManager.CompanyId && x.IsDeleted == false && !new int[] { (int)OrderStatus.StayAssign, (int)OrderStatus.Cancel }.Contains(x.Status)) + .Where(status == 1, x => x.Status == (int)OrderStatus.Assign) + .Where(status == 2, x => new int[] { (int)OrderStatus.Receive, (int)OrderStatus.Travel, (int)OrderStatus.Appear }.Contains(x.Status)) + .Where(status == 3, x => new int[] { (int)OrderStatus.Complete, (int)OrderStatus.Leave, (int)OrderStatus.Sign, (int)OrderStatus.ArriveHome }.Contains(x.Status)) + .Where(status == 4, x => x.Status == (int)OrderStatus.Evaluate) + .Where(startTime.IsNotNull(), x => x.CreatedTime >= startTime) + .Where(endTime.IsNotNull(), x => x.CreatedTime <= endTime) + .Where(key.IsNotNull(), x => x.OrderVehiclePerson.Contains(key) || x.VehicleCode.Contains(key) || x.OrderContent.Contains(key) || x.ProjectName.Contains(key)) + .OrderByDescending(x => x.ArriveDate) + .Select(x => new OrderListOutput + { + Id = x.Id, + VehicleCode = x.VehicleCode, + ArriveDate = x.ArriveDate, + Status = x.Status, + OrderContent = x.OrderContent, + OrderSource = x.OrderSource, + OrderVehiclePerson = x.OrderVehiclePerson, + AssignUserId = x.AssignUserId, + ProjectId = x.ProjectId, + ProjectName = x.ProjectName + }) + .ToPagedListAsync(currentPage, pageSize); + var userIds = orders.Items.Select(x => x.AssignUserId).ToArray(); + var users = await _userRepository.DetachedEntities + .Where(x => userIds.Contains(x.Id)) + .Select(x => new User + { + Id = x.Id, + UserName = x.UserName + }) + .ToListAsync(); + + + + foreach (var item in orders.Items) + { + item.OrderContent = HtmlHelper.ReplaceHtmlMark(item.OrderContent); + item.AssignUserName = users.Find(x => x.Id == item.AssignUserId)?.UserName; + item.StatusName = typeof(OrderStatus).GetDescription(item.Status); + if (new int[] { (int)OrderStatus.Assign }.Contains(item.Status)) + { + item.StatusName = "未接单"; + } + if (new int[] { (int)OrderStatus.Receive, (int)OrderStatus.Travel, (int)OrderStatus.Appear }.Contains(item.Status)) + { + item.StatusName = "已接单"; + } + if (new int[] { (int)OrderStatus.Complete, (int)OrderStatus.Sign, (int)OrderStatus.Leave, (int)OrderStatus.ArriveHome }.Contains(item.Status)) + { + item.StatusName = "已完工"; + } + + item.OrderVehicleDriverName = (await _orderVehicleRepository.DetachedEntities.FirstOrDefaultAsync(x => x.OrderId == item.Id && x.IsDriver == true))?.UserName; + item.OrderTitle = item.ProjectName.IsNull() ? (item.OrderContent.Length >= 13 ? item.OrderContent.Substring(0, 13).Trim().ToString() : item.ProjectName.Trim()) : (item.ProjectName.Length >= 13 ? item.ProjectName.Substring(0, 13).Trim().ToString() : item.ProjectName.Trim()); + } + return orders; + } + + #endregion + + #region 任务统计 + /// + /// 任务统计--车辆 + /// + /// + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/order/statistics/vehicle/search")] + public async Task> GetOrderStatisticsByVehicleAsync(DateTime startTime, DateTime endTime, int currentPage = 1, int pageSize = 10) + { + string where = ""; + if (new long[] { (long)RoleStatusEnum.Salesman, (long)RoleStatusEnum.PartTimeSalesman }.Contains(_userManager.RoleId)) + { + where = $"AND SalesmanId={_userManager.UserId} "; + } + var orderList = await @$"SELECT VehicleCode,VehicleId, + Count(CASE WHEN `Status`>=20 THEN VehicleId END) AS AssignCount, + Count(CASE WHEN `Status`>=30 THEN VehicleId END) AS ReceiveCount, + COUNT(CASE WHEN `Status`>=50 THEN VehicleId END) AS CompleteCount + FROM dc_order WHERE `Status`!=101 AND CompanyId = @companyId AND IsOutside = FALSE AND VehicleId > 0 AND ArriveDate >= @startTime AND ArriveDate <= @endTime {where} + GROUP BY VehicleId,VehicleCode + ORDER BY AssignCount DESC,ReceiveCount DESC,CompleteCount DESC" + .SqlQueryAsync(new { companyId = _userManager.CompanyId, startTime = startTime, endTime = endTime }); + PagedList pagedList = new PagedList + { + Items = orderList.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(), + TotalCount = orderList.Count() + }; + return pagedList; + } + + /// + /// 任务统计--工程 + /// + /// + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/order/statistics/project/search")] + public async Task> GetOrderStatisticsByProjectAsync(DateTime startTime, DateTime endTime, int currentPage = 1, int pageSize = 10) + { + string where = ""; + if (new long[] { (long)RoleStatusEnum.Salesman, (long)RoleStatusEnum.PartTimeSalesman }.Contains(_userManager.RoleId)) + { + where = $"AND SalesmanId={_userManager.UserId} "; + } + var orderList = await @$"SELECT ProjectName,ProjectId, + Count(CASE WHEN `Status`>=10 THEN ProjectId END) AS AssignCount, + Count(CASE WHEN `Status`>=30 THEN ProjectId END) AS ReceiveCount, + COUNT(CASE WHEN `Status`>=50 THEN ProjectId END) AS CompleteCount + FROM dc_order WHERE `Status`!=101 AND CompanyId=@companyId AND ProjectId > 0 AND ArriveDate >= @startTime AND ArriveDate <= @endTime {where} + GROUP BY ProjectId,ProjectName + ORDER BY AssignCount DESC,ReceiveCount DESC,CompleteCount DESC" + .SqlQueryAsync(new { companyId = _userManager.CompanyId, startTime = startTime, endTime = endTime }); + PagedList pagedList = new PagedList + { + Items = orderList.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(), + TotalCount = orderList.Count() + }; + return pagedList; + } + + /// + /// 任务统计--人员 + /// + /// + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/order/statistics/employee/search")] + public async Task> GetOrderStatisticsByEmployeeAsync(DateTime startTime, DateTime endTime, int currentPage = 1, int pageSize = 10) + { + string where = ""; + if (new long[] { (long)RoleStatusEnum.Salesman, (long)RoleStatusEnum.PartTimeSalesman }.Contains(_userManager.RoleId)) + { + where = $"AND o.SalesmanId={_userManager.UserId} "; + } + var orderList = await @$"SELECT ov.UserName,ov.UserId, + Count(CASE WHEN o.`Status`>=10 THEN ov.UserId END) AS AssignCount, + Count(CASE WHEN o.`Status`>=30 THEN ov.UserId END) AS ReceiveCount, + COUNT(CASE WHEN o.`Status`>=50 THEN ov.UserId END) AS CompleteCount + FROM dc_order o + INNER JOIN dc_order_vehicle ov ON o.Id=ov.OrderId + WHERE o.`Status`!=101 AND o.CompanyId=@companyId AND ov.UserId > 0 AND o.ArriveDate >= @startTime AND o.ArriveDate <= @endTime {where} + GROUP BY ov.UserId,ov.UserName + ORDER BY AssignCount DESC,ReceiveCount DESC,CompleteCount DESC" + .SqlQueryAsync(new { companyId = _userManager.CompanyId, startTime = startTime, endTime = endTime }); + PagedList pagedList = new PagedList + { + Items = orderList.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(), + TotalCount = orderList.Count() + }; + return pagedList; + } + + + + /// + /// 任务统计--施工单位 + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/order/statistics/construction/search")] + [AllowAnonymous] + public async Task> GetOrderStatisticsByConstructionAsync(DateTime startTime, DateTime endTime) + { + + var orders = await _repository.DetachedEntities + .Where(x => x.ConstructionId > 0 && x.ProjectId > 0 && x.CompanyId == 265147171168325 && x.ArriveDate >= startTime && x.ArriveDate < endTime) + .GroupBy(x => new { x.ConstructionId, x.ProjectName }).Select(g => new OrderStatisticsConstructionOutput + { + ConstructionId = g.Key.ConstructionId, + ProjectName = g.Key.ProjectName, + AssignCount = g.Count(x => x.Status < 60), + CompleteCount = g.Count(x => x.Status >= 60), + Evaluation = 0 + }).ToListAsync(); + + List orderStatisticsConstructionOutputList = new List(); + var constructionIds = orders.Select(x => x.ConstructionId).Distinct().ToList(); + foreach (var constructionId in constructionIds) + { + OrderStatisticsConstructionOutputs orderStatisticsConstructionOutput = new OrderStatisticsConstructionOutputs(); + orderStatisticsConstructionOutput.ConstructionName = (await _constructionRpository.FirstOrDefaultAsync(x => x.Id == constructionId)).ConstructionName; + orderStatisticsConstructionOutput.AssignCount = orders.Where(x => x.ConstructionId == constructionId).Select(x => x.AssignCount).Sum(); + orderStatisticsConstructionOutput.CompleteCount = orders.Where(x => x.ConstructionId == constructionId).Select(x => x.CompleteCount).Sum(); + orderStatisticsConstructionOutput.Evaluation = 0; + orderStatisticsConstructionOutput.Projects = orders.Where(x => x.ConstructionId == constructionId).ToList(); + orderStatisticsConstructionOutputList.Add(orderStatisticsConstructionOutput); + } + return orderStatisticsConstructionOutputList; + } + + + + #endregion + + #region 公共类 + public class OrderVehicleCompara : IEqualityComparer + { + public bool Equals(OrderVehicle x, OrderVehicle y) + { + bool result = true; + if (x.UserId != y.UserId || x.IsDriver != y.IsDriver) + { + result = false; + } + return result; + } + + public int GetHashCode(OrderVehicle obj) + { + return 0; + } + } + + + + + /// + /// + /// + /// + /// + /// + /// + /// + public async Task GetProjectId(decimal latitude, decimal longitude, string address, string projectName) + { + + var project = await _projectRepository.FirstOrDefaultAsync(x => x.ProjectName == projectName && x.CompanyId == _userManager.CompanyId && x.IsEnabled); + if (project.IsNull()) + { + project = (await _projectRepository.InsertNowAsync(new Project() + { + CompanyId = _userManager.CompanyId, + ProjectName = projectName, + SalesmanId = 0, + Longitude = longitude, + Latitude = latitude, + Address = address, + IsEnabled = true, + ConstructionId = 0, + ConstructionName = "" + })).Entity; + } + await _cacheService.RemoveProjectListAsync(_userManager.CompanyId); + await _cacheService.RemoveProjectAsync(project.Id); + + return project.Id; + + + } + + + /// + /// + /// + /// + /// + /// + public async Task GetConstructionId(long constructionId, string constructionName) + { + + var construction = await _constructionRpository.FirstOrDefaultAsync(x => x.Id == constructionId && x.ConstructionName == constructionName && x.Status); + if (construction.IsNull()) + { + construction = (await _constructionRpository.InsertNowAsync(new Construction() + { + CompanyId = _userManager.CompanyId, + ConstructionName = constructionName, + ContactName = "", + ContactPhone = "", + Status = true + })).Entity; + } + return construction.Id; + } + + + /// + /// + /// + /// + /// + /// . + /// + /// + private async Task UpdateProjectAddressAsync(long projectId, decimal latitude, decimal longitude, string address) + { + + var project = await _projectRepository.FirstOrDefaultAsync(x => x.Id == projectId); + if (project.IsNotNull()) + { + project.Latitude = latitude; + project.Longitude = longitude; + project.Address = address; + await _projectRepository.UpdateNowAsync(project); + + } + await _cacheService.RemoveProjectAsync(projectId); + await _cacheService.RemoveProjectListAsync(_userManager.CompanyId); + } + } +} + + + + + #endregion + \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/OrderVehicle/Dto/Input/OrderVehicleAddInput.cs b/src/Znyc.Dispatching.Application/OrderVehicle/Dto/Input/OrderVehicleAddInput.cs new file mode 100644 index 0000000..6ead555 --- /dev/null +++ b/src/Znyc.Dispatching.Application/OrderVehicle/Dto/Input/OrderVehicleAddInput.cs @@ -0,0 +1,28 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class OrderVehicleAddInput + { + + /// + /// 指派任务人员Id + /// + public long UserId { get; set; } + + /// + /// 姓名 + /// + public string UserName { get; set; } + + /// + /// 电话 + /// + public string UserPhone { get; set; } + + /// + /// 是否司机 + /// + public bool IsDriver { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/OrderVehicle/Dto/OutPut/OrderVehicleListOutput .cs b/src/Znyc.Dispatching.Application/OrderVehicle/Dto/OutPut/OrderVehicleListOutput .cs new file mode 100644 index 0000000..72855bc --- /dev/null +++ b/src/Znyc.Dispatching.Application/OrderVehicle/Dto/OutPut/OrderVehicleListOutput .cs @@ -0,0 +1,49 @@ +using System; + +namespace Znyc.Dispatching.Application +{ + /// + /// + public class OrderVehicleListOutput + { + /// + /// OrderId + /// + public long Id { get; set; } + + /// + /// 订单内容 + /// + public string OrderContent { get; set; } + + /// + /// 状态,,10=待指派,20=已指派,未接单,30=已接单,40=已出发,50=已完成(已签单),60=已离开,70=已评价 + /// + public int Status { get; set; } + + /// + /// 状态名称 + /// + public string StatusName { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车组人员 + /// + public string OrderVehiclePerson { get; set; } + + /// + /// 是否司机 + /// + public bool IsDriver { get; set; } + + /// + /// 创建时间 + /// + public DateTime CreatedTime { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/OrderVehicle/Dto/OutPut/OrderVehicleOutput.cs b/src/Znyc.Dispatching.Application/OrderVehicle/Dto/OutPut/OrderVehicleOutput.cs new file mode 100644 index 0000000..e576ba4 --- /dev/null +++ b/src/Znyc.Dispatching.Application/OrderVehicle/Dto/OutPut/OrderVehicleOutput.cs @@ -0,0 +1,28 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class OrderVehicleOutput + { + + /// + /// UserId + /// + public long UserId { get; set; } + + /// + /// 姓名 + /// + public string UserName { get; set; } + + /// + /// 电话 + /// + public string UserPhone { get; set; } + + /// + /// 是否司机 + /// + public bool IsDriver { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/OrderVisa/Dto/Input/OrderVisaInput.cs b/src/Znyc.Dispatching.Application/OrderVisa/Dto/Input/OrderVisaInput.cs new file mode 100644 index 0000000..5feaa40 --- /dev/null +++ b/src/Znyc.Dispatching.Application/OrderVisa/Dto/Input/OrderVisaInput.cs @@ -0,0 +1,12 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class OrderVisaInput + { + /// + /// 图片路径 + /// + public string Picture { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/OrderVisa/Dto/OutPut/OrderVisaOutput.cs b/src/Znyc.Dispatching.Application/OrderVisa/Dto/OutPut/OrderVisaOutput.cs new file mode 100644 index 0000000..7b7cada --- /dev/null +++ b/src/Znyc.Dispatching.Application/OrderVisa/Dto/OutPut/OrderVisaOutput.cs @@ -0,0 +1,13 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class OrderVisaOutput + { + + /// + /// 图片路径 + /// + public string Picture { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Project/Dto/Input/ProjectAddInput.cs b/src/Znyc.Dispatching.Application/Project/Dto/Input/ProjectAddInput.cs new file mode 100644 index 0000000..ad1efa9 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Project/Dto/Input/ProjectAddInput.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// 工程输入实体 + /// + public class ProjectAddInput + { + /// + /// 工程名称 + /// + [Required(ErrorMessage = "请录入工程名称!")] + public string ProjectName { get; set; } + + /// + /// 业务员Id + /// + public long SalesmanId { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 工地联系人Id + /// + public List projectPersons { get; set; } + + /// + /// 是否启用 + /// + public bool IsEnabled { get; set; } + + /// + /// 施工单位 + /// + public long ConstructionId { get; set; } + + /// + /// 施工单位 + /// + public string ConstructionName { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Project/Dto/Input/ProjectUpdateInput.cs b/src/Znyc.Dispatching.Application/Project/Dto/Input/ProjectUpdateInput.cs new file mode 100644 index 0000000..8bc6a13 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Project/Dto/Input/ProjectUpdateInput.cs @@ -0,0 +1,9 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class ProjectUpdateInput : ProjectAddInput + { + public long Id { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Project/Dto/OutPut/ProjectListOutput.cs b/src/Znyc.Dispatching.Application/Project/Dto/OutPut/ProjectListOutput.cs new file mode 100644 index 0000000..fd8f4ec --- /dev/null +++ b/src/Znyc.Dispatching.Application/Project/Dto/OutPut/ProjectListOutput.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class ProjectListOutput + { + /// + /// Id + /// + public long Id { get; set; } + + /// + /// 工程名称 + /// + public string ProjectName { get; set; } + + /// + /// 工程地址 + /// + public string Address { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 工地联系人(报单人) + /// + public List ProjectPeoples { get; set; } + + /// + /// 是否启用 + /// + public bool IsEnabled { get; set; } + + /// + /// 业务员Id + /// + public long SalesmanId { get; set; } + + /// + /// 施工单位 + /// + public long ConstructionId { get; set; } + } + + public class ProjectListOutputs + { + public string Char { get; set; } + + public List List { get; set; } + } + + public class ProjectListPage + { + public long Total { get; set; } + + public List ProjectList { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Application/Project/Dto/OutPut/ProjectOutput.cs b/src/Znyc.Dispatching.Application/Project/Dto/OutPut/ProjectOutput.cs new file mode 100644 index 0000000..cdbb3eb --- /dev/null +++ b/src/Znyc.Dispatching.Application/Project/Dto/OutPut/ProjectOutput.cs @@ -0,0 +1,63 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class ProjectOutput + { + + /// + /// Id + /// + public long Id { get; set; } + /// + /// 工程名称 + /// + public string ProjectName { get; set; } + + /// + /// 业务员Id + /// + public long SalesmanId { get; set; } + + /// + /// 业务员 + /// + public string Salesman { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 工地联系人(报单人) + /// + public List ProjectPeoples { get; set; } + + /// + /// 是否启用 + /// + public bool IsEnabled { get; set; } + + /// + /// 施工单位 + /// + public long ConstructionId { get; set; } + + + /// + /// 施工单位 + /// + public string ConstructionName { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Application/Project/Services/IProjectService.cs b/src/Znyc.Dispatching.Application/Project/Services/IProjectService.cs new file mode 100644 index 0000000..90b82a6 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Project/Services/IProjectService.cs @@ -0,0 +1,48 @@ +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + /// + /// 工程服务 + /// + public interface IProjectService + { + + /// + /// 查询单个工程信息 + /// + /// + Task GetByIdAsync(long projectId); + + /// + /// 工程列表 + /// + /// + /// + /// + /// + /// + Task PageAsync(int currentPage, int pageSize, int isEnabled, string key); + + /// + /// 新增工程信息 + /// + /// + /// + Task AddAsync(ProjectAddInput input); + + /// + /// 更新公司信息 + /// + /// + /// + Task UpdateAsync(ProjectUpdateInput input); + + /// + /// 停用工程信息 + /// + /// + /// + Task UpdateIsEnabledAsync(long projectId); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Project/Services/ProjectService.cs b/src/Znyc.Dispatching.Application/Project/Services/ProjectService.cs new file mode 100644 index 0000000..b66a0b2 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Project/Services/ProjectService.cs @@ -0,0 +1,294 @@ +using Furion.DatabaseAccessor; +using Furion.DatabaseAccessor.Extensions; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Mapster; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Common.Extensions; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Helpers; + +namespace Znyc.Dispatching.Application +{ + /// + /// 工程管理 + /// + [ApiDescriptionSettings(Name = "project", Order = 32)] + public class ProjectService : IProjectService, IDynamicApiController, ITransient + { + private string[] INDEX_STRINGS = {"A", "B", "C", "D", "E", "F", "G", "H", "I", + "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", + "W", "X", "Y", "Z", "#"}; + private readonly ICacheService _cacheService; + private readonly IRepository _repository; + private readonly IUserManager _userManager; + private readonly IRepository _projectPersonRepository; + private readonly IRepository _constructionRepository; + public ProjectService( + IUserManager userManager, + ICacheService cacheService, + IRepository projectPersonRepository, + IRepository repository, + IRepository constructionRepository) + { + _repository = repository; + _userManager = userManager; + _cacheService = cacheService; + _projectPersonRepository = projectPersonRepository; + _constructionRepository = constructionRepository; + } + + + /// + /// 查询单个工程信息 + /// + /// + [HttpGet] + [Route("api/v1/project/{projectId}")] + public async Task GetByIdAsync(long projectId) + { + ProjectOutput project = await _cacheService.GetProjectAsync(projectId); + project.Salesman = (await _cacheService.GetEmployeeListAsync(_userManager.CompanyId)).Find(x => x.UserId == project.SalesmanId)?.EmployeeName; + return project; + } + + + /// + /// 工程列表 + /// + /// -1全部,停用0,正常1 + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/projects/search")] + public async Task PageAsync([Required] int currentPage, [Required] int pageSize, [FromQuery] int isEnabled, [FromQuery] string key) + { + var projects = (await _cacheService.GetProjectListAsync(_userManager.CompanyId)) + .WhereIf(isEnabled >= 0, x => x.IsEnabled == (isEnabled == 0 ? false : true)) + .WhereIf(new long[] { (long)RoleStatusEnum.Salesman, (long)RoleStatusEnum.PartTimeSalesman }.Contains(_userManager.RoleId), + x => x.SalesmanId == _userManager.UserId) + .WhereIf(key.IsNotEmptyOrNull(), x => x.ProjectName.Contains(key)) + .Adapt>(); + + var projectOutputs = new List(); + foreach (var INDEX_STRING in INDEX_STRINGS) + { + projectOutputs.Add(new ProjectListOutputs() + { + Char = INDEX_STRING, + List = projects.Where(x => StringHelper.GetStringFirstSpell(x.ProjectName) == INDEX_STRING).ToList() + }); + }; + var data = new ProjectListPage() + { + ProjectList = projectOutputs, + Total = projects.Count + }; + return data; + } + + + /// + /// 新增工程信息 + /// + /// + /// + [HttpPost] + [Route("api/v1/project")] + public async Task AddAsync(ProjectAddInput input) + { + var entity = await _repository.Where(x => x.ProjectName == input.ProjectName && x.CompanyId == _userManager.CompanyId).FirstOrDefaultAsync(); + if (entity.IsNotNull()) + { + if (entity.IsEnabled) + { + throw Oops.Bah("该名称" + input.ProjectName + "已存在"); + } + else + { + throw Oops.Bah("该名称" + input.ProjectName + "已存在,且您已停用"); + } + } + var project = input.Adapt(); + project.CompanyId = _userManager.CompanyId; + project.IsEnabled = true; + if (new long[] { (long)RoleStatusEnum.Salesman, (long)RoleStatusEnum.PartTimeSalesman }.Contains(_userManager.RoleId)) + { + project.SalesmanId = _userManager.UserId; + } + var result = await _repository.InsertNowAsync(project); + foreach (var item in input.projectPersons) + { + var projectPersons = item.Adapt(); + projectPersons.ProjectId = result.Entity.Id; + await _projectPersonRepository.InsertNowAsync(projectPersons); + } + + await _cacheService.RemoveProjectAsync(_userManager.CompanyId); + await _cacheService.RemoveProjectListAsync(_userManager.CompanyId); + } + + /// + /// 更新工程信息 + /// + /// + /// + [HttpPut] + [Route("api/v1/project")] + [UnitOfWork] + public async Task UpdateAsync(ProjectUpdateInput input) + { + var project = await _repository.FirstOrDefaultAsync(x => x.Id == input.Id); + if (project.IsNull()) throw Oops.Oh("暂无该信息"); + var repeatProject = await _repository.DetachedEntities + .Where(x => x.ProjectName == input.ProjectName && x.Id != input.Id && + x.CompanyId == _userManager.CompanyId) + .FirstOrDefaultAsync(); + if (repeatProject.IsNotNull()) + { + if (repeatProject.IsEnabled) + { + throw Oops.Bah("该名称" + input.ProjectName + "已存在"); + } + else + { + throw Oops.Bah("该名称" + input.ProjectName + "已存在,且您已停用"); + } + } + #region 修改工程联系人 + var oldProjectPersons = await _projectPersonRepository.DetachedEntities + .Where(x => x.ProjectId == input.Id && x.IsDeleted == false) + .ToListAsync(); + var oldProjectPersonIds = oldProjectPersons.Select(x => x.ProjectPersonId).ToArray(); + var newProjectPersonIds = input.projectPersons.Select(x => x.ProjectPersonId).ToArray(); + var deleteProjectPersonIds = oldProjectPersonIds.Except(newProjectPersonIds).ToArray(); + if (deleteProjectPersonIds.Length > 0) + { + for (int i = 0; i < deleteProjectPersonIds.Length; i++) + { + var projectPerson = oldProjectPersons.FirstOrDefault(x => x.ProjectPersonId == deleteProjectPersonIds[i]); + projectPerson.IsDeleted = true; + await _projectPersonRepository.UpdateNowAsync(projectPerson); + } + } + foreach (var item in input.projectPersons) + { + var projectPerson = oldProjectPersons.Find(x => x.ProjectPersonId == item.ProjectPersonId); + if (projectPerson == null) + { + var projectPersons = item.Adapt(); + projectPersons.ProjectId = input.Id; + await _projectPersonRepository.InsertNowAsync(projectPersons); + } + } + #endregion + if (new long[] { (long)RoleStatusEnum.Salesman, (long)RoleStatusEnum.PartTimeSalesman }.Contains(_userManager.RoleId)) + { + input.SalesmanId = _userManager.UserId; + } + if (input.ProjectName != project.ProjectName || input.SalesmanId != project.SalesmanId) + { + //同步修改订单表工程信息 + await "update dc_order set ProjectName=@projectName,SalesmanId=@salesmanId where ProjectId=@id And IsDeleted=0" + .SqlNonQueryAsync(new { id = input.Id, projectName = input.ProjectName, salesmanId = input.SalesmanId }); + } + var result = await _repository.UpdateNowAsync(input.Adapt(project)); + if (result.IsNull()) + { + throw Oops.Oh("修改工程信息失败"); + } + + await _cacheService.RemoveProjectListAsync(_userManager.CompanyId); + await _cacheService.RemoveProjectAsync(input.Id); + } + + + /// + /// 停用工程信息 + /// + /// + /// + [HttpPut] + [Route("api/v1/project/{projectId}")] + public async Task UpdateIsEnabledAsync(long projectId) + { + var project = await _repository.FindOrDefaultAsync(projectId); + if (project.IsNull()) throw Oops.Oh("暂无该信息"); + project.IsEnabled = false; + var result = await _repository.UpdateNowAsync(project); + if (result.IsNull()) + { + throw Oops.Oh("停用工程信息失败"); + } + await _cacheService.RemoveProjectListAsync(_userManager.CompanyId); + await _cacheService.RemoveProjectAsync(projectId); + } + + + #region v1.2.7 + + + [HttpGet] + [UnitOfWork] + [Route("api/v1/project/autoinsert/{projectName}/{constructionName}")] + public async Task AutoInsertProjectAsync([Required] string projectName, [Required] string constructionName) + { + projectName = projectName.Trim(); + constructionName = constructionName.Trim(); + //新增施工单位 + var constructionEntity = (await _constructionRepository.DetachedEntities.FirstOrDefaultAsync(x => x.CompanyId == _userManager.CompanyId && x.ConstructionName == constructionName)); + if (constructionEntity.IsNull()) + { + Construction construction = new Construction(); + construction.CompanyId = _userManager.CompanyId; + construction.ConstructionName = constructionName; + construction.ContactName = ""; + construction.ContactPhone = ""; + construction.Status = true; + constructionEntity = (await _constructionRepository.InsertNowAsync(construction))?.Entity; + if (constructionEntity.Id < 0) + { + throw Oops.Oh("新增施工单位失败"); + } + } + //新增工程 + var projectEntity = (await _repository.DetachedEntities.FirstOrDefaultAsync(x => x.CompanyId == _userManager.CompanyId && x.ProjectName == projectName)); + if (projectEntity.IsNull()) + { + Project project = new Project(); + project.CompanyId = _userManager.CompanyId; + project.ProjectName = projectName; + project.SalesmanId = 0; + project.Longitude = 0; + project.Latitude = 0; + project.Address = ""; + project.IsEnabled = true; + project.ConstructionId = constructionEntity.Id; + project.ConstructionName = constructionName; + projectEntity = (await _repository.InsertNowAsync(project)).Entity; + } + + await _cacheService.RemoveProjectListAsync(_userManager.CompanyId); + await _cacheService.RemoveProjectAsync(projectEntity.Id); + + return new ProjectOutput() + { + ConstructionId = constructionEntity.Id, + ConstructionName = constructionName, + Id = projectEntity.Id, + ProjectName = projectName, + }; + } + #endregion + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/ProjectPerson/Dto/Input/ProjectPersonAddInput.cs b/src/Znyc.Dispatching.Application/ProjectPerson/Dto/Input/ProjectPersonAddInput.cs new file mode 100644 index 0000000..170b2fa --- /dev/null +++ b/src/Znyc.Dispatching.Application/ProjectPerson/Dto/Input/ProjectPersonAddInput.cs @@ -0,0 +1,25 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// 公司输入实体 + /// + public class ProjectPersonAddInput + { + /// + /// 联系人Id,链接员工表Id + /// + public long ProjectPersonId { get; set; } + + /// + /// 联系人姓名 + /// + + public string ProjectPersonName { get; set; } + + /// + /// 联系人电话 + /// + + public string ProjectPersonPhone { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/ProjectPerson/Dto/Input/ProjectPersonUpdateInput.cs b/src/Znyc.Dispatching.Application/ProjectPerson/Dto/Input/ProjectPersonUpdateInput.cs new file mode 100644 index 0000000..dd550d3 --- /dev/null +++ b/src/Znyc.Dispatching.Application/ProjectPerson/Dto/Input/ProjectPersonUpdateInput.cs @@ -0,0 +1,9 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class ProjectPersonUpdateInput : ProjectPersonAddInput + { + public long Id { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/ProjectPerson/Dto/OutPut/ProjectPersonOutput.cs b/src/Znyc.Dispatching.Application/ProjectPerson/Dto/OutPut/ProjectPersonOutput.cs new file mode 100644 index 0000000..b0d4ca5 --- /dev/null +++ b/src/Znyc.Dispatching.Application/ProjectPerson/Dto/OutPut/ProjectPersonOutput.cs @@ -0,0 +1,22 @@ +namespace Znyc.Dispatching.Application +{ + public class ProjectPersonOutput + { + /// + /// 联系人Id,链接员工表Id + /// + public long ProjectPersonId { get; set; } + + /// + /// 联系人姓名 + /// + + public string ProjectPersonName { get; set; } + + /// + /// 联系人电话 + /// + + public string ProjectPersonPhone { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Application/ProjectPerson/Services/IProjectPersonService.cs b/src/Znyc.Dispatching.Application/ProjectPerson/Services/IProjectPersonService.cs new file mode 100644 index 0000000..ace83ee --- /dev/null +++ b/src/Znyc.Dispatching.Application/ProjectPerson/Services/IProjectPersonService.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IProjectPersonService + { + Task> GetByIdAsync(long id); + } +} diff --git a/src/Znyc.Dispatching.Application/ProjectPerson/Services/ProjectPersonService.cs b/src/Znyc.Dispatching.Application/ProjectPerson/Services/ProjectPersonService.cs new file mode 100644 index 0000000..73b83c8 --- /dev/null +++ b/src/Znyc.Dispatching.Application/ProjectPerson/Services/ProjectPersonService.cs @@ -0,0 +1,44 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Application +{ + /// + ///工程信息联系人管理 + /// + [ApiDescriptionSettings(Name = "projectperson", Order = 31)] + public class ProjectPersonService : IProjectPersonService, IDynamicApiController, ITransient + { + private readonly IRepository _repository; + + public ProjectPersonService(IRepository repository) + { + _repository = repository; + } + + /// + /// 根据工程Id查询工程联系人 + /// + /// + [HttpGet] + [Route("api/v1/project/persons/{projectId}")] + public async Task> GetByIdAsync(long projectId) + { + List projectPeoples = await _repository.DetachedEntities + .Where(x => x.ProjectId == projectId && x.IsDeleted == false) + .Select(x => new ProjectPersonOutput + { + ProjectPersonName = x.ProjectPersonName, + ProjectPersonPhone = x.ProjectPersonPhone + }).ToListAsync(); + return projectPeoples; + } + } +} diff --git a/src/Znyc.Dispatching.Application/Report/Dto/Input/ReportAddInput.cs b/src/Znyc.Dispatching.Application/Report/Dto/Input/ReportAddInput.cs new file mode 100644 index 0000000..9146696 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Report/Dto/Input/ReportAddInput.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + public class ReportAddInput + { + /// + /// 反馈明细 + /// + [Required] + public string ReportContent { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Report/Services/IReportService.cs b/src/Znyc.Dispatching.Application/Report/Services/IReportService.cs new file mode 100644 index 0000000..9ed109a --- /dev/null +++ b/src/Znyc.Dispatching.Application/Report/Services/IReportService.cs @@ -0,0 +1,9 @@ +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IReportService + { + Task InsertAsync(ReportAddInput input); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Report/Services/ReportService.cs b/src/Znyc.Dispatching.Application/Report/Services/ReportService.cs new file mode 100644 index 0000000..bc8ff4f --- /dev/null +++ b/src/Znyc.Dispatching.Application/Report/Services/ReportService.cs @@ -0,0 +1,51 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Mapster; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Application +{ + /// + /// 意见反馈服务 + /// + [ApiDescriptionSettings(Name = "report", Order = 100)] + public class ReportService : IReportService, IDynamicApiController, ITransient + { + private readonly IProjectService _companyService; + private readonly IRepository _employeeRepository; + private readonly IRepository _repository; + private readonly UserManager _userManager; + + public ReportService(IRepository repository, + IRepository employeeRepository, + UserManager userManager, + IProjectService companyService + ) + { + _repository = repository; + _employeeRepository = employeeRepository; + _userManager = userManager; + _companyService = companyService; + } + + /// + /// 添加意见反馈 + /// + /// + /// + [HttpPost] + public async Task InsertAsync(ReportAddInput input) + { + Report report = input.Adapt(); + report.ReportUserId = _userManager.UserId; + report.ReportTime = DateTime.Now; + report.Note = ""; + await _repository.InsertNowAsync(report); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Role/Dto/OutPut/RoleOutput.cs b/src/Znyc.Dispatching.Application/Role/Dto/OutPut/RoleOutput.cs new file mode 100644 index 0000000..c0b35e1 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Role/Dto/OutPut/RoleOutput.cs @@ -0,0 +1,23 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// RoleOutput + /// + public class RoleOutput + { + /// + /// Id + /// + public long Id { get; set; } + + /// + /// 名称 + /// + public string Name { get; set; } + + /// + /// 权限备注 + /// + public string Intro { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Role/Services/IRoleService.cs b/src/Znyc.Dispatching.Application/Role/Services/IRoleService.cs new file mode 100644 index 0000000..4c7a612 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Role/Services/IRoleService.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IRoleService + { + Task> GetRoleAsync(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Role/Services/RoleService.cs b/src/Znyc.Dispatching.Application/Role/Services/RoleService.cs new file mode 100644 index 0000000..0903e78 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Role/Services/RoleService.cs @@ -0,0 +1,58 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Application +{ + /// + /// 角色服务 + /// + [ApiDescriptionSettings(Name = "role", Order = 40)] + public class RoleService : IRoleService, IDynamicApiController, ITransient + { + private readonly ICacheService _cache; + private readonly IRepository _repository; + + public RoleService( + IRepository repository, + ICacheService cache + ) + { + _repository = repository; + _cache = cache; + } + + /// + /// 获取角色 + /// + /// + [HttpGet] + [AllowAnonymous] + public async Task> GetRoleAsync() + { + List roles = await _cache.GetRoleAsync(); + if (roles.IsNull()) + { + roles = await _repository.DetachedEntities + .Where(x => x.Status == CommonStatusEnum.ENABLE) + .Select(x => new RoleOutput + { + Id = x.Id, + Name = x.Name + }).ToListAsync(); + await _cache.SetRoleAsync(roles); + } + + return roles; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/RoleMenu/Dto/OutPut/RoleMenuListOutput.cs b/src/Znyc.Dispatching.Application/RoleMenu/Dto/OutPut/RoleMenuListOutput.cs new file mode 100644 index 0000000..db75842 --- /dev/null +++ b/src/Znyc.Dispatching.Application/RoleMenu/Dto/OutPut/RoleMenuListOutput.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class RoleMenuListOutput + { + public long RoleId { get; set; } + + public List MenuList { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/RoleMenu/Services/IRoleMenuService.cs b/src/Znyc.Dispatching.Application/RoleMenu/Services/IRoleMenuService.cs new file mode 100644 index 0000000..723b9cb --- /dev/null +++ b/src/Znyc.Dispatching.Application/RoleMenu/Services/IRoleMenuService.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IRoleMenuService + { + /// + /// 获取角色的菜单Id集合 + /// + /// + /// + Task> GetRoleMenuIdList(List roleIdList); + + /// + /// 获取角色菜单 + /// + /// + Task> GetRoleMenuListAsync(); + + /// + /// 同步角色菜单 + /// + /// + Task> GetRoleMenuListByIdAsync(long roleId); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/RoleMenu/Services/RoleMenuService.cs b/src/Znyc.Dispatching.Application/RoleMenu/Services/RoleMenuService.cs new file mode 100644 index 0000000..78ad7ae --- /dev/null +++ b/src/Znyc.Dispatching.Application/RoleMenu/Services/RoleMenuService.cs @@ -0,0 +1,132 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Mapster; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Application +{ + /// + /// 角色菜单服务 + /// + [ApiDescriptionSettings(Name = "rolemenu", Order = 146)] + public class RoleMenuService : IRoleMenuService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _menuRepository; + private readonly IRepository _repository; + private readonly IUserManager _userManager; + + public RoleMenuService( + IRepository repository, + IRepository menuRepository, + IUserManager userManager, + ICacheService cacheService) + { + _repository = repository; + _cacheService = cacheService; + _menuRepository = menuRepository; + _userManager = userManager; + } + + /// + /// 获取角色的菜单Id集合 + /// + /// + /// + [HttpGet] + public async Task> GetRoleMenuIdList(List roleIdList) + { + return await _repository.DetachedEntities + .Where(u => roleIdList.Contains(u.RoleId)) + .Select(u => u.MenuId).ToListAsync(); + } + + /// + /// 获取角色的菜单 + /// + /// + [HttpGet] + [Route("api/v1/menus")] + public async Task> GetRoleMenuListAsync() + { + var list = await _cacheService.GetRoleMenuAsync(_userManager.RoleId); + if (list.IsNull() || list.Count < 1) + { + var menus = await (from p in _repository.Where(x => x.RoleId == _userManager.RoleId && x.IsDeleted == false) + .AsQueryable() + join d in _menuRepository.AsQueryable().Include(u => u.Childrens) + .Where(x => x.ParentId == 0 && x.IsShow && x.IsDeleted == false).AsQueryable() on p.MenuId equals d.Id + select new Menu + { + Id = d.Id, + Name = d.Name, + ParentId = d.ParentId, + Layers = d.Layers, + Code = d.Code, + Type = d.Type, + Icon = d.Icon, + Router = d.Router, + Permission = d.Permission, + IsFrame = d.IsFrame, + IsExpand = d.IsExpand, + IsShow = d.IsShow, + Sort = d.Sort, + Childrens = d.Childrens + }).OrderBy(x => x.Sort).ToListAsync(); + + list = menus.Adapt>(); + await _cacheService.SetRoleMenuAsync(_userManager.RoleId, list); + } + return list; + } + + + /// + /// 同步角色菜单 + /// + /// + [HttpGet] + [AllowAnonymous] + public async Task> GetRoleMenuListByIdAsync(long roleId) + { + var list = await _cacheService.GetRoleMenuAsync(roleId); + if (list.IsNull() || list.Count < 1) + { + var menus = await (from p in _repository.Where(x => x.RoleId == roleId && x.IsDeleted == false) + .AsQueryable() + join d in _menuRepository.AsQueryable().Include(u => u.Childrens) + .Where(x => x.ParentId == 0 && x.IsShow == true && x.IsDeleted == false).AsQueryable() on p.MenuId equals d.Id + select new Menu + { + Id = d.Id, + Name = d.Name, + ParentId = d.ParentId, + Layers = d.Layers, + Code = d.Code, + Type = d.Type, + Icon = d.Icon, + Router = d.Router, + Permission = d.Permission, + IsFrame = d.IsFrame, + IsExpand = d.IsExpand, + IsShow = d.IsShow, + Sort = d.Sort, + Childrens = d.Childrens + }).OrderBy(x => x.Sort).ToListAsync(); + + list = menus.Adapt>(); + await _cacheService.SetRoleMenuAsync(roleId, list); + } + return list; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/User/Dto/Input/DecryptPhoneAddInput.cs b/src/Znyc.Dispatching.Application/User/Dto/Input/DecryptPhoneAddInput.cs new file mode 100644 index 0000000..40ca9ac --- /dev/null +++ b/src/Znyc.Dispatching.Application/User/Dto/Input/DecryptPhoneAddInput.cs @@ -0,0 +1,23 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + /// + public class DecryptPhoneAddInput + { + /// + /// jscode + /// + public string JsCode { get; set; } + + /// + /// EncryptedData + /// + public string EncryptedData { get; set; } + + /// + /// Iv + /// + public string Iv { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Application/User/Dto/Input/UserAddInput.cs b/src/Znyc.Dispatching.Application/User/Dto/Input/UserAddInput.cs new file mode 100644 index 0000000..8dbc27f --- /dev/null +++ b/src/Znyc.Dispatching.Application/User/Dto/Input/UserAddInput.cs @@ -0,0 +1,41 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application.Dto.Input +{ + /// + /// 用户输入实体 + /// + public class UserAddInput + { + /// + /// 用户名 + /// + [Required(ErrorMessage = "用户名不能为空")] + public string UserName { get; set; } + + /// + /// 头像 + /// + [Required(ErrorMessage = "头像不能为空")] + public string AvatarUrl { get; set; } + + /// + /// + /// + [Required(ErrorMessage = "DecryptPhone不能为空")] + public DecryptPhoneAddInput DecryptPhoneAddInput { get; set; } + + /// + /// 公司Id + /// + [Required(ErrorMessage = "请确认要加入的公司")] + public long CompanyId { get; set; } + + /// + /// 角色Id + /// + [Required(ErrorMessage = "请选择角色")] + public long RoleId { get; set; } + } + +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/User/Dto/Input/UserChangePwdInput.cs b/src/Znyc.Dispatching.Application/User/Dto/Input/UserChangePwdInput.cs new file mode 100644 index 0000000..7d71fbc --- /dev/null +++ b/src/Znyc.Dispatching.Application/User/Dto/Input/UserChangePwdInput.cs @@ -0,0 +1,37 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application.Dto.Input +{ + /// + /// 用户修改密码 + /// + public class UserChangePwdInput + { + /// + /// 手机号 + /// + [MaxLength(11, ErrorMessage = "手机号不能超过11位")] + [RegularExpression("^[1][3,4,5,6,7,8,9][0-9]{9}$", ErrorMessage = "请输入正确的手机号码")] + public string Account { get; set; } + + /// + /// 旧密码 + /// + public string OldPassWord { get; set; } + + /// + /// 新密码 + /// + public string PassWord { get; set; } + + /// + /// 确认密码 + /// + public string RePassWord { get; set; } + + /// + /// 验证码 + /// + public string VerifyCode { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/User/Dto/Input/UserUpdateInput.cs b/src/Znyc.Dispatching.Application/User/Dto/Input/UserUpdateInput.cs new file mode 100644 index 0000000..eea35de --- /dev/null +++ b/src/Znyc.Dispatching.Application/User/Dto/Input/UserUpdateInput.cs @@ -0,0 +1,32 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application.Dto.Input +{ + /// + /// 用户输入实体 + /// + public class UserUpdateInput + { + public long Id { get; set; } + + /// + /// 用户名 + /// + [MaxLength(8)] + [Required(ErrorMessage = "用户名不能为空")] + public string UserName { get; set; } + + /// + /// 头像 + /// + [Required(ErrorMessage = "头像不能为空")] + public string AvatarUrl { get; set; } + + /// + /// 电话 + /// + [MaxLength(11)] + [Required(ErrorMessage = "电话不能为空")] + public string Phone { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/User/Dto/Output/UserOutput.cs b/src/Znyc.Dispatching.Application/User/Dto/Output/UserOutput.cs new file mode 100644 index 0000000..dd55d12 --- /dev/null +++ b/src/Znyc.Dispatching.Application/User/Dto/Output/UserOutput.cs @@ -0,0 +1,42 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// 用户输出实体 + /// + public class UserOutput + { + /// + /// + public long Id { get; set; } + + /// + /// + public string AvatarUrl { get; set; } + + /// + /// + public string UserName { get; set; } + + /// + /// + public long RoleId { get; set; } + + /// + /// + public string RoleName { get; set; } + + /// + /// + public long CompanyId { get; set; } + + /// + /// + public string CompanyName { get; set; } + + /// + /// 电话 + /// + public string Phone { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/User/Services/IUserService.cs b/src/Znyc.Dispatching.Application/User/Services/IUserService.cs new file mode 100644 index 0000000..aa630d6 --- /dev/null +++ b/src/Znyc.Dispatching.Application/User/Services/IUserService.cs @@ -0,0 +1,22 @@ +using System.Threading.Tasks; +using Znyc.Dispatching.Application.Dto.Input; + +namespace Znyc.Dispatching.Application +{ + public interface IUserService + { + /// + /// 邀请用户注册并登陆 + /// + /// + /// + Task RegisterUserAsync(UserAddInput input); + + /// + /// 修改用户信息 + /// + /// + /// + Task UpdateAsync(UserUpdateInput input); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/User/Services/UserService.cs b/src/Znyc.Dispatching.Application/User/Services/UserService.cs new file mode 100644 index 0000000..fb7ee02 --- /dev/null +++ b/src/Znyc.Dispatching.Application/User/Services/UserService.cs @@ -0,0 +1,440 @@ +using Furion.DatabaseAccessor; +using Furion.DataEncryption; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Newtonsoft.Json; +using Senparc.Weixin.WxOpen.Helpers; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Threading.Tasks; +using Znyc.Dispatching.Application.Dto.Input; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.WeChat.Core.CommonService.TemplateMessage.WxOpen; + +namespace Znyc.Dispatching.Application +{ + /// + /// 用户服务 + /// + [ApiDescriptionSettings(Name = "user", Order = 10)] + public class UserService : IUserService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _companyRepository; + private readonly IRepository _employeeRepository; + private readonly IRepository _repository; + private readonly SmsProviderOptions _smsProviderOptions; + private readonly IUserManager _userManager; + private readonly WeixinSettingOptions _weixinSettingOptions; + private readonly IRepository _userRoleRepository; + private readonly IWxUserRelationService _wxUserRelationService; + private readonly IRoleMenuService _roleMenuService; + private readonly ILogger _logger; + private readonly IRepository _vehiclePersonRepository; + private readonly IRepository _projectPersonRepository; + public UserService( + IUserManager userManager, + ICacheService cacheService, + IRepository companyRepository, + IRepository repository, + IRepository employeeRepository, + IRepository userRoleRepository, + IOptions smsProviderOptions, + IWxUserRelationService wxUserRelationService, + IRoleMenuService roleMenuService, + IOptions weixinSettingOptions, + ILogger logger, + IRepository vehiclePersonRepository, + IRepository projectPersonRepository) + { + _repository = repository; + _userManager = userManager; + _cacheService = cacheService; + _companyRepository = companyRepository; + _employeeRepository = employeeRepository; + _smsProviderOptions = smsProviderOptions.Value; + _weixinSettingOptions = weixinSettingOptions.Value; + _userRoleRepository = userRoleRepository; + _wxUserRelationService = wxUserRelationService; + _roleMenuService = roleMenuService; + _logger = logger; + _vehiclePersonRepository = vehiclePersonRepository; + _projectPersonRepository = projectPersonRepository; + } + + /// + /// 个人资料 + /// + /// + [HttpGet] + [Route("api/v1/user")] + public async Task GetUserAsync() + { + var userOutput = await _cacheService.GetUserAsync(_userManager.UserId); + if (userOutput.IsNull()) + { + var user = await _repository.Where(x => x.Id == _userManager.UserId).Select(x => new + { + x.Id, + x.UserName, + x.Phone, + x.AvatarUrl + }).FirstOrDefaultAsync(); + + var employeeList = await _employeeRepository.Where(x => x.UserId == user.Id && x.Status == (int)CommonStatusEnum.ENABLE).ToListAsync(); + var cIds = employeeList.Select(x => x.CompanyId).ToArray(); + //有管理员优先登陆管理员 + if (employeeList.Any(x => x.RoleId == (int)RoleStatusEnum.Administrator)) + { + cIds = employeeList.Where(x => x.RoleId == (long)RoleStatusEnum.Administrator).Select(x => x.CompanyId).ToArray(); + } + var company = await _companyRepository.Where(x => cIds.Contains(x.Id) && x.Status == (int)CommonStatusEnum.ENABLE).Select(x => new + { + x.Id, + x.CompanyName + }).FirstOrDefaultAsync(); + var employee = employeeList.Where(x => x.CompanyId == company.Id).Select(x => new + { + x.RoleId, + x.RoleName, + x.CompanyId, + x.UserId, + x.EmployeeName, + x.IsDefault + }).FirstOrDefault(); + + userOutput = new UserOutput + { + Id = user.Id, + AvatarUrl = user.AvatarUrl, + UserName = employee.EmployeeName, + RoleId = employee.RoleId, + RoleName = employee.RoleName, + CompanyId = employee.CompanyId, + CompanyName = company.CompanyName, + Phone = user.Phone + }; + await _cacheService.SetUserAsync(userOutput); + } + return userOutput; + } + + /// + /// 邀请用户注册并登陆 + /// + /// + /// + [HttpPost] + [AllowAnonymous] + [UnitOfWork] + [Route("api/v1/user/register")] + public async Task RegisterUserAsync(UserAddInput input) + { + var jsCode2JsonResult = + await SnsApi.JsCode2JsonAsync(_weixinSettingOptions.WxOpenAppId, _weixinSettingOptions.WxOpenAppSecret, + input.DecryptPhoneAddInput.JsCode); + if (jsCode2JsonResult.IsNull()) + { + throw Oops.Bah("jsCode2JsonResult为空"); + } + var company = await _companyRepository.FindOrDefaultAsync(input.CompanyId); + if (company.IsNull()) throw Oops.Bah("公司不存在"); + + if (company.Status == (int)CommonStatusEnum.REVIEW) + { + throw Oops.Bah("您注册公司正在审核中,请稍等").StatusCode(4012); + } + if (company.Status == (int)CommonStatusEnum.DISABLE) + { + throw Oops.Bah("公司已被停用,请联系管理员"); + } + var user = await _repository.FirstOrDefaultAsync(x => x.OpenId == jsCode2JsonResult.openid); + var employee = new Employee(); + if (user.IsNull()) + { + //解密电话 + string phone = " "; + if (input.DecryptPhoneAddInput.EncryptedData.IsNotNull() && input.DecryptPhoneAddInput.Iv.IsNotNull()) + { + try + { + var rijndael = new RijndaelManaged + { + BlockSize = 128, + Mode = CipherMode.CBC, + Padding = PaddingMode.PKCS7 + }; + + var encryptedData = Convert.FromBase64String(input.DecryptPhoneAddInput.EncryptedData); + var key = Convert.FromBase64String(jsCode2JsonResult.session_key);//第一步获取到的session_key + var iv = Convert.FromBase64String(input.DecryptPhoneAddInput.Iv); + + var decryptor = rijndael.CreateDecryptor(key, iv); + using (var msDecrypt = new MemoryStream(encryptedData)) + { + using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) + { + using (var srDecrypt = new StreamReader(csDecrypt)) + { + var plaintext = srDecrypt.ReadToEnd(); + var json = Newtonsoft.Json.JsonConvert.DeserializeObject(plaintext); + var phoneNumber = json.phoneNumber; + var purePhoneNumber = json.purePhoneNumber; + //至此,成功获取到手机号 + phone = Convert.ToString(purePhoneNumber); + } + } + } + } + catch (Exception ex) + { + Console.WriteLine($"RegisterUserAsync:{ex.StackTrace}"); + _logger.LogError(ex.StackTrace); + } + } + + //用户 + var userEntity = await _repository.InsertNowAsync(new User + { + OpenId = jsCode2JsonResult.openid, + UserName = input.UserName, + AvatarUrl = input.AvatarUrl, + Phone = phone, + Status = CommonStatusEnum.ENABLE + }); + var isDefault = input.RoleId == (int)RoleStatusEnum.Outside ? false : true; + //员工 + var employeeEntity = await _employeeRepository.InsertNowAsync(new Employee + { + UserId = userEntity.Entity.Id, + AvatarUrl = input.AvatarUrl, + EmployeeName = input.UserName, + EmployeePhone = phone, + CompanyId = input.CompanyId, + RoleId = input.RoleId, + RoleName = typeof(RoleStatusEnum).GetDescription(input.RoleId.ObjToInt()), + IsDefault = isDefault, + Status = (int)CommonStatusEnum.ENABLE + }); + //用户角色 + //await _userRoleRepository.InsertNowAsync(new UserRole + //{ + // UserId = userEntity.Entity.Id, + // RoleId = input.RoleId + //}); + //清除员工列表Cache + await _cacheService.RemoveEmployeeListAsync(input.CompanyId); + //用户中间表 + await _wxUserRelationService.AddOrUpdateAsync(userEntity.Entity.Id, jsCode2JsonResult.openid, jsCode2JsonResult.unionid); + user = userEntity.Entity; + employee = employeeEntity.Entity; + } + else + { + employee = await _employeeRepository.Where(x => x.UserId == user.Id && x.Status == (int)CommonStatusEnum.ENABLE && x.CompanyId == input.CompanyId).FirstOrDefaultAsync(); + if (employee.IsNull()) + { + var employeenew = new Employee + { + UserId = user.Id, + AvatarUrl = input.AvatarUrl, + EmployeeName = input.UserName, + EmployeePhone = user.Phone, + CompanyId = input.CompanyId, + RoleId = input.RoleId, + RoleName = typeof(RoleStatusEnum).GetDescription((int)input.RoleId), + IsDefault = true, + Status = (int)CommonStatusEnum.ENABLE + }; + + Console.WriteLine($"{JsonConvert.SerializeObject(employeenew)}"); + var isDefault = input.RoleId == (int)RoleStatusEnum.Outside ? false : true; + + //员工 + var employeeEntity = await _employeeRepository.InsertNowAsync(new Employee + { + UserId = user.Id, + AvatarUrl = input.AvatarUrl, + EmployeeName = input.UserName, + EmployeePhone = user.Phone, + CompanyId = input.CompanyId, + RoleId = input.RoleId, + RoleName = typeof(RoleStatusEnum).GetDescription(input.RoleId.ObjToInt()), + IsDefault = isDefault, + Status = (int)CommonStatusEnum.ENABLE + }); + employee = employeeEntity.Entity; + company = new Company() { Id = input.CompanyId }; + } + } + // 生成 token + string accessToken = JWTEncryption.Encrypt(new Dictionary + { + {ClaimConst.CLAINM_USERID, user.Id}, + {ClaimConst.CLAINM_COMPANYID, company.Id}, + {ClaimConst.CLAINM_ROLEID, employee.RoleId}, + {ClaimConst.CLAINM_USERNAME, user.UserName}, + {ClaimConst.CLAINM_SUPERADMIN,new long[] { (long)RoleStatusEnum.Administrator, (long)RoleStatusEnum.Scheduling,(long)RoleStatusEnum.CarCaptain }.Contains(employee.RoleId) } + }); + //RedisToken + await _cacheService.SetTokenAsync(user.Id, accessToken); + + await _cacheService.RemoveEmployeeListAsync(input.CompanyId); + LoginOutput loginOutput = new LoginOutput() + { + Token = accessToken, + Menus = await _roleMenuService.GetRoleMenuListByIdAsync(employee.RoleId) + }; + switch (employee.RoleId) + { + case (long)RoleStatusEnum.Administrator: + case (long)RoleStatusEnum.Scheduling: + case (long)RoleStatusEnum.CarCaptain: + case (long)RoleStatusEnum.Salesman: + case (long)RoleStatusEnum.Financial: + case (long)RoleStatusEnum.WareHouse: + case (long)RoleStatusEnum.PartTimeSalesman: + loginOutput.Url = CommonConst.DEFAULT_SUPERADMIN_INDEX; + break; + case (long)RoleStatusEnum.CrewMembers: + case (long)RoleStatusEnum.ProjectPerson: + loginOutput.Url = CommonConst.DEFAULT_DRIVER_INDEX; + break; + case (long)RoleStatusEnum.Outside: + loginOutput.Url = CommonConst.DEFAULT_OUTSIDE_INDEX; + break; + default: + loginOutput.Url = CommonConst.DEFAULT_DRIVER_INDEX; + break; + } + return loginOutput; + + + } + + /// + /// 修改用户信息 + /// + /// + /// + [HttpPut] + [Route("api/v1/user")] + public async Task UpdateAsync(UserUpdateInput input) + { + var user = await _repository.FirstOrDefaultAsync(x => x.Id == input.Id); + if (user.IsNull()) + { + throw Oops.Oh("用户不存在"); + } + var repeatPhone = await _repository.DetachedEntities.FirstOrDefaultAsync(x => x.Id != input.Id && x.Phone == input.Phone); + if (repeatPhone.IsNotNull()) + { + throw Oops.Bah("电话已存在"); + } + user.Phone = input.Phone; + user.UserName = input.UserName; + user.AvatarUrl = CommonConst.Prefix_AvataUrl + input.AvatarUrl[(input.AvatarUrl.LastIndexOf("/") + 1)..]; + await _repository.UpdateNowAsync(user); + + //更新当前用户下所有角色姓名 + var employees =await _employeeRepository.Where(x => x.UserId == user.Id).ToListAsync(); + foreach (var employee in employees) + { + if (employee.IsNotNull()) + { + employee.EmployeePhone = input.Phone; + employee.EmployeeName = input.UserName; + employee.AvatarUrl = CommonConst.Prefix_AvataUrl + input.AvatarUrl[(input.AvatarUrl.LastIndexOf("/") + 1)..]; + await _employeeRepository.UpdateNowAsync(employee); + await _cacheService.RemoveEmployeeAsync(employee.Id); + await _cacheService.RemoveEmployeeListAsync(employee.CompanyId); + } + } + await _cacheService.RemoveUserAsync(user.Id); + //同步车组人员表 + var vehiclePersons = await _vehiclePersonRepository.Where(x => x.IsDeleted == false && x.UserId == input.Id).ToListAsync(); + foreach (var item in vehiclePersons) + { + item.UserName = input.UserName; + item.UserPhone = input.Phone; + await _vehiclePersonRepository.UpdateNowAsync(item); + //删除车组人员Cache + await _cacheService.RemoveVehiclePersonAsync(item.VehicleId); + } + //同步工程联系人表 + var projectPersons = await _projectPersonRepository.Where(x => x.IsDeleted == false && x.ProjectPersonId == input.Id).ToListAsync(); + foreach (var item in projectPersons) + { + item.ProjectPersonName = input.UserName; + item.ProjectPersonPhone = input.Phone; + await _projectPersonRepository.UpdateNowAsync(item); + //清除工程信息Cache + await _cacheService.RemoveProjectAsync(item.ProjectId); + //清除工程列表信息Cache + await _cacheService.RemoveProjectListAsync(_userManager.CompanyId); + } + } + + + + + + /// + /// 更新用户信息 + /// + /// + /// + /// + [HttpPut] + [AllowAnonymous] + public async Task UpdateAsync(string openId, string account) + { + //var user = await _repository.FirstOrDefaultAsync(x => x.Account == account); + //if (user.IsNotNull()) + //{ + // user.OpenId = openId; + // await _repository.UpdateNowAsync(user); + //} + } + + + + /// + /// 解密电话号码 + /// + /// + /// + [HttpPost] + [AllowAnonymous] + [Route("api/v1/decryptphone")] + public async Task DecryptPhoneNumber([FromBody] DecryptPhoneAddInput decryptPhone) + { + var jsCode2JsonResult = await SnsApi.JsCode2JsonAsync(_weixinSettingOptions.WxOpenAppId, _weixinSettingOptions.WxOpenAppSecret, decryptPhone.JsCode); + if (jsCode2JsonResult.IsNull()) + { + throw Oops.Oh("jsCode2JsonResult为空!"); + } + string phone = ""; + if (decryptPhone.EncryptedData.IsNotNull() && decryptPhone.Iv.IsNotNull()) + { + var phoneNumber = EncryptHelper.DecryptPhoneNumberBySessionKey(jsCode2JsonResult.session_key, decryptPhone.EncryptedData, decryptPhone.Iv); + if (phoneNumber.IsNull()) + { + phone = phoneNumber.purePhoneNumber; + } + } + return phone; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/UserRole/Services/IUserRoleService.cs b/src/Znyc.Dispatching.Application/UserRole/Services/IUserRoleService.cs new file mode 100644 index 0000000..6adb413 --- /dev/null +++ b/src/Znyc.Dispatching.Application/UserRole/Services/IUserRoleService.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IUserRoleService + { + Task> GetUserRoleIdList(long userId); + + + Task AddAsync(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/UserRole/Services/UserRoleService.cs b/src/Znyc.Dispatching.Application/UserRole/Services/UserRoleService.cs new file mode 100644 index 0000000..7ddb2c3 --- /dev/null +++ b/src/Znyc.Dispatching.Application/UserRole/Services/UserRoleService.cs @@ -0,0 +1,61 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Application +{ + /// + /// 用户角色服务 + /// + [ApiDescriptionSettings(Name = "userrole", Order = 50)] + public class UserRoleService : IUserRoleService, IDynamicApiController, ITransient + { + private readonly IRepository _repository; + private readonly IUserManager _userManager; + + public UserRoleService( + IRepository repository, + IUserManager userManager + ) + { + _repository = repository; + _userManager = userManager; + } + + /// + /// 获取用户的角色Id集合 + /// + /// + /// + [NonAction] + public async Task> GetUserRoleIdList(long userId) + { + return await _repository.Where(u => u.UserId == userId).Select(u => u.RoleId) + .ToListAsync(); + } + + /// + /// + /// + /// + [HttpGet] + [AllowAnonymous] + public async Task AddAsync() + { + UserRole userRole = new UserRole() + { + UserId = 123123123, + RoleId = CommonConst.DEFAULT_ROLEID_1001 + }; + await _repository.InsertNowAsync(userRole); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/BasicsVehicleUpdateInput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/BasicsVehicleUpdateInput.cs new file mode 100644 index 0000000..6fa89a3 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/BasicsVehicleUpdateInput.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// 基础信息-车辆编辑 + /// + public class BasicsVehicleUpdateInput + { + public long Id { get; set; } + + /// + /// 车辆编号 + /// + [Required(ErrorMessage = "请输入设备名称!")] + [MaxLength(8, ErrorMessage = "设备名称不能超过8位")] + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + [Required(ErrorMessage = "请输入车牌号!")] + [MaxLength(8, ErrorMessage = "车牌号不能超过8位")] + public string VehiclePlate { get; set; } + + /// + /// 状态 + /// + public int Status { get; set; } + + /// + /// 车组人员 + /// + public List VehiclePersons { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/TrackPlayBackCorrectInput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/TrackPlayBackCorrectInput.cs new file mode 100644 index 0000000..374bd6f --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/TrackPlayBackCorrectInput.cs @@ -0,0 +1,43 @@ +using Newtonsoft.Json; + +namespace Znyc.Dispatching.Application +{ + + /// + /// 轨迹纠偏入参 + /// + public class TrackPlayBackCorrectInput + { + /// + /// 维度 + /// + [JsonProperty("y")] + public decimal Latitude { get; set; } + + /// + /// 精度 + /// + [JsonProperty("x")] + public decimal Longitude { get; set; } + + /// + /// 角度 + /// + [JsonProperty("ag")] + public int Direct { get; set; } + + /// + /// 速度 + /// + [JsonProperty("sp")] + public int Speed { get; set; } + + /// + /// 时间 + /// + [JsonProperty("tm")] + public int Timestamp { get; set; } + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/VehicleAddInput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/VehicleAddInput.cs new file mode 100644 index 0000000..42b7cc2 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/VehicleAddInput.cs @@ -0,0 +1,95 @@ +using System; +using Znyc.Dispatching.Core; + +namespace Znyc.Dispatching.Application +{ + public class VehicleAddInput + { + /// + /// 所属公司 + /// + public long CompanyId { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// 车辆类型 + /// + public long VehicleType { get; set; } + + /// + /// 所属车组 + /// + public long VehicleGroup { get; set; } + + /// + /// SIM卡号 + /// + public long SimNo { get; set; } + + /// + /// 设备类型 + /// + public long TerminalType { get; set; } + + /// + /// 设备号 + /// + public long TerminalNo { get; set; } + + /// + /// 联系人 + /// + public string ContactPerson { get; set; } + + /// + /// 司机电话 + /// + public string ContactPhone { get; set; } + + /// + /// 状态(字典 0正常 1停用 2删除) + /// + public CommonStatusEnum Status { get; set; } = CommonStatusEnum.ENABLE; + + /// + /// 打火状态 + /// + public AccStatusEnum Acc { get; set; } = AccStatusEnum.NORMAL; + + /// + /// 工作状态 + /// + public WorkStatusEnum Work { get; set; } = WorkStatusEnum.NORMAL; + + /// + /// IEML号 + /// + public string ImeiNo { get; set; } + + /// + /// GPS时间 + /// + public DateTime? GpsTime { get; set; } + + /// + /// 开通时间 + /// + public DateTime OpenTime { get; set; } + + /// + /// 到期时间 + /// + public DateTime ExpireTime { get; set; } + + public int CardType { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/VehicleUpdateInput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/VehicleUpdateInput.cs new file mode 100644 index 0000000..4f6cde2 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/Input/VehicleUpdateInput.cs @@ -0,0 +1,36 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + public class VehicleUpdateInput + { + public long Id { get; set; } + + /// + /// 车辆编号 + /// + [Required(ErrorMessage = "车辆编号不能为空!")] + [MaxLength(8, ErrorMessage = "车辆编号不能超过8位")] + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + [Required(ErrorMessage = "车牌号不能为空!")] + [MaxLength(8, ErrorMessage = "车牌号不能超过8位")] + public string VehiclePlate { get; set; } + + /// + /// 联系人 + /// + [MaxLength(8, ErrorMessage = "联系人过长")] + public string ContactPerson { get; set; } + + /// + /// 联系人电话 + /// + [MaxLength(11, ErrorMessage = "联系电话不能超过11位")] + [RegularExpression("^[1][3,4,5,6,7,8,9][0-9]{9}$", ErrorMessage = "请输入正确的手机号码")] + public string ContactPhone { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/AlarmOutput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/AlarmOutput.cs new file mode 100644 index 0000000..904f3b1 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/AlarmOutput.cs @@ -0,0 +1,27 @@ +using System; + +namespace Znyc.Dispatching.Application +{ + public class AlarmOutput + { + /// + /// 超速最新未读时间 + /// + public DateTime? OverspeedTime { get; set; } + + /// + /// 超速未读数 + /// + public int OverspeedCount { get; set; } + + /// + /// 自编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/MapMonitorDataOutput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/MapMonitorDataOutput.cs new file mode 100644 index 0000000..f704aeb --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/MapMonitorDataOutput.cs @@ -0,0 +1,242 @@ +using System; + +namespace Znyc.Dispatching.Application +{ + /// + /// 地图 + /// + public class MapMonitorDataOutput + { + public long Id { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 维度 + /// + public decimal Latitude { get; set; } + + /// + /// 精度 + /// + public decimal Longitude { get; set; } + + + /// + /// 图标 + /// + public string IconPath { get; set; } + + + /// + /// + /// + public string Width { get; set; } + + + /// + /// + /// + public string Height { get; set; } + + + + public int Rotate { get; set; } + + + + /// + /// + /// + public Anchor Anchor { get; set; } + + + + /// + /// + /// + public CustomCallout CustomCallout { get; set; } + + + + + ///// + ///// 所属公司 + ///// + //public long CompanyId { get; set; } + + + ///// + ///// 车牌号 + ///// + //public string VehiclePlate { get; set; } + + ///// + ///// 联系人电话 + ///// + //public long VehicleType { get; set; } + + ///// + ///// 联系人 + ///// + //public string ContactPerson { get; set; } + + ///// + ///// 联系电话 + ///// + //public string ContactPhone { get; set; } + + ///// + ///// SimNo + ///// + //public string SimNo { get; set; } + + ///// + ///// 状态(字典 0正常 1停用 2删除) + ///// + //public int Status { get; set; } = 0; + + ///// + ///// 打火状态 + ///// + //public int Acc { get; set; } = 0; + + ///// + ///// 工作状态 + ///// + //public int Work { get; set; } = 0; + + ///// + ///// GPS时间 + ///// + //public string GpsTime { get; set; } + + ///// + ///// Gps服务器接收时间 + ///// + //public string RecTime { get; set; } + + ///// + ///// gps状态 + ///// + //public int GpsState { get; set; } = 0; + + ///// + ///// 方向 + ///// + //public int Direct { get; set; } = 0; + + ///// + ///// 速度 + ///// + //public int Speed { get; set; } = 0; + + ///// + ///// 静止时长 + ///// + //public string DurationTime { get; set; } + + ///// + ///// acc工作时长 + ///// + //public string AccDurationTime { get; set; } + + + + + + ///// + ///// 地点 + ///// + //public string Address { get; set; } + + ///// + ///// work工作时长 + ///// + //public string WorkDurationTime { get; set; } + + ///// + ///// 离线时长 + ///// + //public string OfflineTime { get; set; } + + ///// + ///// 更新时间 + ///// + //public DateTime ModifiedTime { get; set; } + + ///// + ///// IMEL号 + ///// + //public string ImeiNo { get; set; } + + + ///// + ///// 设备类型 + ///// + //public int TerminalType { get; set; } + + ///// + ///// 开通时间 + ///// + //public DateTime OpenTime { get; set; } + + ///// + ///// 到期时间 + ///// + //public DateTime ExpireTime { get; set; } + + ///// + ///// 设备类型 + ///// + //public string TerminalTypeName { get; set; } + + ///// + ///// Gps信号源 + ///// + //public string GpsSignalSource { get; set; } + + + ///// + ///// Gps信号模式 1 GPS,2 基站 + ///// + //public int GpsMode { get; set; } + + ///// + ///// 位置基本信息报警标志位 --欠压 + ///// + //public int GpsAlert { get; set; } + + ///// + ///// 掉电 + ///// + //public int Useing { get; set; } + + + } + + public class Anchor + { + public string X { get; set; } + + public string Y { get; set; } + + } + + public class CustomCallout + { + + public string AnchorY { get; set; } + + public string AnchorX { get; set; } + + public string Display { get; set; } = "ALWAYS"; + + + + } + +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/PgyAlertStraightDtlOutput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/PgyAlertStraightDtlOutput.cs new file mode 100644 index 0000000..a00ded3 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/PgyAlertStraightDtlOutput.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class PgyAlertStraightDtlListOutput + { + /// + /// 总数 + /// + public int TotalCount { get; set; } + + /// + /// 超速记录输出集合 + /// + public List List { get; set; } + } + + /// + /// 超速记录输出实体 + /// + [Serializable] + public class PgyAlertStraightDtlOutput + { + /// + /// 所属车辆 + /// + public long VehicleId { get; set; } + + /// + /// 所属公司 + /// + public long CompanyId { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// GPS时间 + /// + public DateTime GpsTime { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 方向 + /// + public int Direct { get; set; } + + /// + /// 速度 + /// + public int Speed { get; set; } = 0; + + /// + /// 地点 + /// + public string Address { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/TrackPlayBackCorrectOutput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/TrackPlayBackCorrectOutput.cs new file mode 100644 index 0000000..88f7a28 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/TrackPlayBackCorrectOutput.cs @@ -0,0 +1,76 @@ +using Newtonsoft.Json; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + + /// + /// 轨迹纠偏出参 + /// + public class TrackPlayBackCorrectOutput + { + + /// + /// 数据体 + /// + [JsonProperty("data")] + public Data data { get; set; } + + /// + /// 30001错误表示抓路失败。当传入点数较少或较稀疏时,可能会导致抓路失败。 + /// + [JsonProperty("errcode")] + public int ErrCode { get; set; } + + /// + /// + /// + [JsonProperty("errdetail")] + public string ErrDetail { get; set; } + + /// + /// + /// + [JsonProperty("errmsg")] + public string ErrMsg { get; set; } + + + } + + /// + /// 数据体 + /// + public class Data + { + /// + /// 总距离 + /// + [JsonProperty("distance")] + public decimal Distance { get; set; } + + + /// + /// 返回坐标合集 + /// + [JsonProperty("points")] + public List points { get; set; } + } + + /// + /// 返回坐标合集 + /// + public class Points + { + /// + /// 维度 + /// + [JsonProperty("y")] + public decimal Latitude { get; set; } + + /// + /// 经度 + /// + [JsonProperty("x")] + public decimal Longitude { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/TrackPlaybackOutput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/TrackPlaybackOutput.cs new file mode 100644 index 0000000..77e479b --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/TrackPlaybackOutput.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class TrackPlaybackListOutput + { + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// 总公里 + /// + public decimal TotalDistance { get; set; } + + /// + /// 总停留时间 + /// + public string TotalStopTime { get; set; } + + /// + /// 开始时间 + /// + //public DateTime StartTime { get; set; } + + /// + /// 结束时间 + /// + //public DateTime EndTime { get; set; } + + /// + /// 轨迹点输出实体 + /// + public List trackPlaybackOutputs { get; set; } + + /// + /// 停留点输出实体 + /// + public List Stops { get; set; } + } + + public class TrackPlaybackOutput + { + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// GPS时间 + /// + public DateTime GpsTime { get; set; } + + /// + /// 速度 + /// + public int Speed { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 方向 + /// + public int Direct { get; set; } + + /// + /// 开始时间 + /// + public DateTime StartTime { get; set; } + + /// + /// 结束时间 + /// + public DateTime EndTime { get; set; } + + /// + /// 静止时长 + /// + public string DurationTime { get; set; } + + /// + /// 是否是停留点 + /// + public bool IsStopPoint { get; set; } + + /// + /// 停留次数 + /// + public int StopPointIdx { get; set; } + + /// + /// 打火状态 + /// + public int Acc { get; set; } + + /// + /// ACC持续时长 + /// + public string AccDurationTime { get; set; } + + /// + /// 工作状态 + /// + public int Work { get; set; } + + /// + /// 工作持续时长 + /// + public string WorkDurationTime { get; set; } + + /// + /// 总里程 + /// + public decimal TotalDistance { get; set; } + } + + public class Stop + { + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 开始时间 + /// + public DateTime StartTime { get; set; } + + /// + /// 结束时间 + /// + public DateTime EndTime { get; set; } + + /// + /// GPS时间 + /// + public DateTime GpsTime { get; set; } + + /// + /// 状态 + /// + public int Status { get; set; } + + /// + /// 停留点描述 + /// + public string State { get; set; } + + /// + /// 停留时长描述 + /// + public string Behavior { get; set; } + + /// + /// 总里程 + /// + public decimal TotalDistance { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/VehicleBaiscListOutput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/VehicleBaiscListOutput.cs new file mode 100644 index 0000000..121168a --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/VehicleBaiscListOutput.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class VehicleBaiscListOutput + { + public long Id { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// 状态 + /// + public int Status { get; set; } + + /// + /// 车组人员 + /// + public List VehiclePerson { get; set; } + + /// + /// 车组人员姓名 + /// + public string VehiclePersonName { get; set; } + + /// + /// 车组人员电话 + /// + public string VehiclePersonPhone { get; set; } + } + + public class VehicleBaiscListOutputs + { + public string Char { get; set; } + + public List List { get; set; } + + public List VehicleGpsList { get; set; } + + } + + public class VehicleBaiscListPage + { + public long Total { get; set; } + + public List VehicleBaiscList { get; set; } + } + +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/VehicleGpsOutput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/VehicleGpsOutput.cs new file mode 100644 index 0000000..ff8897f --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/VehicleGpsOutput.cs @@ -0,0 +1,207 @@ +using System; + +namespace Znyc.Dispatching.Application +{ + public class VehicleGpsOutput + { + public long Id { get; set; } + + /// + /// 所属公司 + /// + public long CompanyId { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// 联系人 + /// + public string ContactPerson { get; set; } + + /// + /// 联系电话 + /// + public string ContactPhone { get; set; } + + /// + /// 状态(字典 1正常 -1停用 -2删除 0审核中) + /// + public int Status { get; set; } + + + /// + /// 打火状态 + /// + public int Acc { get; set; } + + /// + /// 工作状态 + /// + public int Work { get; set; } + + /// + /// Gps状态 + /// + public int GpsState { get; set; } + + /// + /// Gps状态名称 + /// + public string GpsStateName { get; set; } + + /// + /// GPS时间 + /// + public string GpsTime { get; set; } + + /// + /// 最后通讯时间 + /// + public string RecTime { get; set; } + + /// + /// 速度 + /// + public int Speed { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// ACC持续时长 + /// + public string AccDurationTime { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// IMEI号 + /// + public string ImeiNo { get; set; } + + /// + /// 设备类型 + /// + public int TerminalType { get; set; } + + /// + /// 开通时间 + /// + public DateTime OpenTime { get; set; } + + /// + /// 到期时间 + /// + public DateTime ExpireTime { get; set; } + + /// + /// 设备类型 + /// + public string TerminalTypeName { get; set; } + + /// + /// 离线时长 + /// + public string OfflineTime { get; set; } + + + /// + /// work工作时长 + /// + public string WorkDurationTime { get; set; } + + /// + /// 静止时长 + /// + public string DurationTime { get; set; } + + /// + /// 是否开启超速报警 + /// + public bool IsOverspeedAlarm { get; set; } + + /// + /// 超速速度 + /// + public int Overspeed { get; set; } + + /// + /// 是否激活 + /// + public bool IsActivate { get; set; } + + /// + /// 是否开启GPS + /// + public bool IsGps { get; set; } + + /// + /// Sim卡号 + /// + public string SimNo { get; set; } + + /// + /// 更新时间 + /// + public DateTime ModifiedTime { get; set; } + + /// + /// Gps信号模式 1 GPS,2 基站 + /// + public int GpsMode { get; set; } + + /// + /// 车辆任务状态 + /// + public int VehicleTaskStatus { get; set; } + + /// + /// 车组人员 + /// + //public List VehiclePerson { get; set; } + public string VehiclePerson { get; set; } + + /// + /// 位置基本信息报警标志位 --欠压 + /// + public int GpsAlert { get; set; } + + /// + /// Gps信号源 + /// + public string GpsSignalSource { get; set; } + + /// + /// 掉电 + /// + public int Useing { get; set; } + + /// + /// 排序 + /// + public int Sort { get; set; } + /// + /// 方向 + /// + public int Direct { get; set; } = 0; + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/VehicleListOutput.cs b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/VehicleListOutput.cs new file mode 100644 index 0000000..4c15bd3 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Dto/OutPut/VehicleListOutput.cs @@ -0,0 +1,89 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + public class VehicleListOutput + { + /// + /// 全部数 + /// + public int AllCount { get; set; } + + /// + /// 离线数 + /// + public int OfflineCount { get; set; } + + /// + /// 静止数 + /// + public int StillCount { get; set; } + + /// + /// 行驶数 + /// + public int DrivingCount { get; set; } + + public List vehicleGpsOutput { get; set; } + } + + //public class VehicleOutput + //{ + // public long Id { get; set; } + + // /// + // /// 所属公司 + // /// + // public long CompanyId { get; set; } + + // /// + // /// 车辆编号 + // /// + // public string VehicleCode { get; set; } + + // /// + // /// 车牌号 + // /// + // public string VehiclePlate { get; set; } + + // /// + // /// 联系人 + // /// + // public string VehicleDriverName { get; set; } + + // /// + // /// 司机电话 + // /// + // public string DriverPhone { get; set; } + + // /// + // /// 状态(字典 0正常 1停用 2删除) + // /// + // public int Status { get; set; } + + // /// + // /// gps状态 + // /// + // public int GpsState { get; set; } + + // /// + // /// 速度 + // /// + // public int Speed { get; set; } + + // /// + // /// 工作时长 + // /// + // public string DurationTime { get; set; } + + // /// + // /// acc工作时长 + // /// + // public string AccDurationTime { get; set; } + + // /// + // /// work工作时长 + // /// + // public string WorkDurationTime { get; set; } + //} +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Services/IVehicleService.cs b/src/Znyc.Dispatching.Application/Vehicle/Services/IVehicleService.cs new file mode 100644 index 0000000..86a24c1 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Services/IVehicleService.cs @@ -0,0 +1,125 @@ +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IVehicleService + { + + #region v1.2.0 + /// + /// 根据id获取车辆Gps信息 + /// + /// + /// + Task GetVehicleGpsByIdAsync(long vehicleId); + + /// + /// 获取地图信息 + /// + /// + Task> GetMapMonitorAsync(); + + /// + /// 分页查询 + /// + /// + /// + /// + /// + /// + //Task PageAsync([Required] int gpsState, [Required] int currentPage, [Required] int pageSize, [FromQuery] string key); + + /// + /// 更新车辆信息 + /// + /// + /// + Task UpdateAsync(VehicleUpdateInput input); + + /// + /// 轨迹回放纠偏 + /// + /// + /// + /// + /// + Task TrackPlaybackCorrectionAsync(long vehicleId, DateTime startTime, DateTime endTime); + + + /// + /// 修改超速报警/速度 + /// + /// + /// + /// + /// + Task UpdateOverSpeedAsync(long vehicleId, bool isOverspeedAlarm, int overspeed); + + /// + /// 超速记录 + /// + /// + /// + /// + Task MbAlertSpeedByTime([Required] int currentPage = 1, + [Required] int pageSize = 10); + + /// + /// 未读报警消息数 + /// + /// + Task UnreadAlarmCountAsync(); + + + /// + /// 同步轨迹 + /// + /// + Task SyncTrackPlaybackCorrectionAsync(DateTime startTime, DateTime endTime, string type); + + #endregion + + + + #region v1.2.1 + /// + /// 基础数据-车辆管理列表 + /// + /// + /// + /// + /// + /// + Task BasicsPageAsync([Required] int currentPage, [Required] int pageSize, [FromQuery] int status, [FromQuery] string key); + + /// + /// 基础数据-车辆信息 + /// + /// + /// + Task GetVehicleBasicsByIdAsync(long vehicleId); + + /// + /// 更新车辆基础信息 + /// + /// + /// + Task BasicsUpdateAsync(BasicsVehicleUpdateInput input); + + /// + /// 分页查询 + /// + /// + /// 0全部,1任务中,2空闲,3停用 + /// + /// + /// + Task PageAsync([Required] int status = 0, [Required] int currentPage = 1, + [Required] int pageSize = 10, [FromQuery] string key = null); + #endregion + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Vehicle/Services/VehicleService.cs b/src/Znyc.Dispatching.Application/Vehicle/Services/VehicleService.cs new file mode 100644 index 0000000..f547f1f --- /dev/null +++ b/src/Znyc.Dispatching.Application/Vehicle/Services/VehicleService.cs @@ -0,0 +1,1255 @@ +using Furion.DatabaseAccessor; +using Furion.DatabaseAccessor.Extensions; +using Furion.DataValidation; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Mapster; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using MongoDB.Driver; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Application.Services; +using Znyc.Dispatching.Common.Extensions; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Helpers; +using Znyc.Dispatching.MongoDb.Repository.Collection; +using Znyc.Dispatching.MongoDb.Repository.Repositorys; + +namespace Znyc.Dispatching.Application +{ + /// + /// 车辆信息服务 + /// + [ApiDescriptionSettings(Name = "vehicle", Order = 146)] + public class VehicleService : IVehicleService, IDynamicApiController, ITransient + { + private string[] INDEX_STRINGS = {"A", "B", "C", "D", "E", "F", "G", "H", "I", + "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", + "W", "X", "Y", "Z", "#"}; + private readonly ICacheService _cacheService; + private readonly IRepository _employeeRepository; + private readonly IGpsRealTimeRepository _gpsRealTimeRepository; + private readonly IMongodbBaseRepository _mongodbBaseRepository; + private readonly IPgyAlertStraightDtlRepository _pgyAlertStraightGtlRepository; + private readonly IRepository _repository; + private readonly IUserManager _userManager; + private readonly IRepository _userRepository; + private readonly IDictionaryService _dictionaryService; + private readonly ILogger _logger; + private readonly IRepository _vehiclePersonRepository; + private readonly IRepository _orderRepository; + private readonly IRepository _oilRepository; + + public VehicleService( + IRepository repository, + IGpsRealTimeRepository gpsRealTimeRepository, + IRepository employeeRepository, + IRepository userRepository, + IPgyAlertStraightDtlRepository pgyAlertStraightGtlRepository, + ICacheService cacheService, + IUserManager userManager, + IDictionaryService dictionaryService, + IMongodbBaseRepository mongodbBaseRepository, + IRepository vehiclePersonRepository, + IRepository orderRepository, + IRepository oilRepository, + ILogger logger) + { + _repository = repository; + _userManager = userManager; + _gpsRealTimeRepository = gpsRealTimeRepository; + _employeeRepository = employeeRepository; + _userRepository = userRepository; + _pgyAlertStraightGtlRepository = pgyAlertStraightGtlRepository; + _cacheService = cacheService; + _mongodbBaseRepository = mongodbBaseRepository; + _dictionaryService = dictionaryService; + _logger = logger; + _vehiclePersonRepository = vehiclePersonRepository; + _orderRepository = orderRepository; + _oilRepository = oilRepository; + } + + /// + /// 根据id获取车辆Gps信息 + /// + /// + /// + [HttpGet] + [Route("api/v1/vehicle/gps/{vehicleId}")] + public async Task GetVehicleGpsByIdAsync(long vehicleId) + { + //车辆 + Vehicle vehicle = await _cacheService.GetVehicleAsync(vehicleId); + //公司 + CompanyOutput company = await _cacheService.GetCompanyAsync(_userManager.CompanyId, _userManager.UserId); + //gps数据 + GpsRealTime gpsRealTime = await _gpsRealTimeRepository.GetGpsRealTimeByVehicleId(vehicleId); + + if(gpsRealTime.IsNotNull()) + { + var Timeres = TimeHelper.ExecDateDiff(gpsRealTime.GpsTime.AddHours(8), DateTime.Now); + if (Timeres > 15) + gpsRealTime.GpsState = 0; + } + + VehicleGpsOutput vehicleGpsOutput = new VehicleGpsOutput + { + Id = vehicle.Id, + CompanyId = vehicle.CompanyId, + ContactPerson = vehicle.ContactPerson, + ContactPhone = vehicle.ContactPhone, + VehicleCode = vehicle.VehicleCode, + VehiclePlate = vehicle.VehiclePlate, + Acc = gpsRealTime?.Acc ?? 0, + Work = gpsRealTime?.Work ?? 0, + Status = vehicle.Status, + ImeiNo = vehicle.ImeiNo, + Speed = gpsRealTime?.Speed ?? 0, + TerminalType = (int)vehicle.TerminalType, + OpenTime = vehicle.OpenTime, + Direct = gpsRealTime?.Direct ?? 0, + ExpireTime = vehicle.ExpireTime, + AccDurationTime = gpsRealTime?.AccDurationTime ?? "0分钟", + IsOverspeedAlarm = vehicle.IsOverspeedAlarm, + GpsTime = gpsRealTime?.GpsTime.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss") ?? "未激活", + Address = gpsRealTime?.Address?? "暂无位置", + Overspeed = vehicle.Overspeed, + GpsMode = gpsRealTime?.GpsMode??2, + GpsAlert = gpsRealTime.IsNull()? 1 :gpsRealTime.GpsAlert, + Useing = gpsRealTime.IsNull() ? 1:gpsRealTime.Useing, + GpsState = gpsRealTime.IsNull() ? 0:gpsRealTime.GpsState, + WorkDurationTime = gpsRealTime?.WorkDurationTime ?? "0分钟", + DurationTime = gpsRealTime?.DurationTime ?? "0分钟", + RecTime = gpsRealTime?.RecTime.AddHours(8).ToString("yyyy-MM-dd HH:mm-ss") ?? "未激活", + OfflineTime = gpsRealTime.IsNull() || + gpsRealTime?.RecTime < Convert.ToDateTime("2000-01-01 00:00:00.000") + ? "未激活" + : StringHelper.ShowTimeInterval(gpsRealTime?.RecTime.AddHours(8)), + + GpsSignalSource = "卫星", + TerminalTypeName = + typeof(TerminalTypeEnum).GetDescription((int)TerminalTypeEnum.BSJKGM_08) ?? "未知设备型号", + Latitude = gpsRealTime.IsNull() ? company.Latitude : gpsRealTime.Latitude, + Longitude = gpsRealTime.IsNull() ? company.Longitude : gpsRealTime.Longitude + }; + return vehicleGpsOutput; + } + + /// + /// 获取地图信息 + /// + /// + [HttpGet] + [Route("api/v1/maps")] + public async Task> GetMapMonitorAsync() + { + List vehicleGpsOutput = new List(); + List gpsRealTimels = new List(); + + if(_userManager.CompanyId != 0) + { + //车辆 + vehicleGpsOutput = (await _cacheService.GetVehicleByCompanyIdAsync(_userManager.CompanyId)) + .Where(x => x.IsActivate && x.IsGps).ToList(); + gpsRealTimels = await _gpsRealTimeRepository.GetGpsRealTimeByCompanyId(_userManager.CompanyId); + } + else + { + await _cacheService.RemoveAllVehicleByCompanyIdAsync(); + //车辆 + vehicleGpsOutput = (await _cacheService.GetAllVehicleByCompanyIdAsync()) + .Where(x => x.IsActivate && x.IsGps).ToList(); + var carID = vehicleGpsOutput.Select(x =>x.Id).ToList(); + gpsRealTimels = await _gpsRealTimeRepository.GetGpsRealTimeListByVehicleId(carID); + } + + //公司 + var company = await _cacheService.GetCompanyAsync(_userManager.CompanyId, _userManager.UserId); + //返回地图数据 + var mapMonitorList = new List(); + foreach (VehicleGpsOutput vehicle in vehicleGpsOutput) + { + var mapMonitorDataOutput = new MapMonitorDataOutput + { + Id = vehicle.Id, + VehicleCode = vehicle.VehicleCode, + Longitude = vehicle.Longitude, + Latitude = vehicle.Latitude, + + Width = "17px", + Height = "30px", + Anchor = new Anchor() + { + X = ".5", + Y = ".5" + }, + CustomCallout = new CustomCallout() + { + AnchorX = "0", + AnchorY = ".5", + Display = "ALWAYS" + } + + }; + var gpsRealTime = gpsRealTimels.FirstOrDefault(x => x.VehicleId == vehicle.Id); + if (gpsRealTime.IsNotNull()) + { + var Path = gpsRealTime.GpsState == 0 ? "stop" : gpsRealTime.GpsState == 1 ? "road" : "static"; + + mapMonitorDataOutput.Rotate = gpsRealTime?.Direct ?? 0; + mapMonitorDataOutput.Longitude = gpsRealTime?.Longitude ?? company.Longitude; + mapMonitorDataOutput.Latitude = gpsRealTime?.Latitude ?? company.Latitude; + mapMonitorDataOutput.IconPath = "/map/static/images/index/" + Path + ".png"; + }; + mapMonitorList.Add(mapMonitorDataOutput); + } + return mapMonitorList; + } + + /// + /// 分页查询 + /// + /// + /// 0全部,1任务中,2空闲,3停用 + /// + /// + /// + [HttpGet] + [Route("api/v1/vehicles/search")] + public async Task PageAsync([Required] int status = -1, [Required] int currentPage = 1, + [Required] int pageSize = 10, [FromQuery] string key = null) + { + + + List vehicles = new List(); + if (_userManager.CompanyId != 0) + { + //车辆 + vehicles = (await _cacheService.GetVehicleByCompanyIdAsync(_userManager.CompanyId)) + .Where(x => x.IsActivate && x.IsGps).ToList(); + } + else + { + //车辆 + vehicles = (await _cacheService.GetAllVehicleByCompanyIdAsync()) + .Where(x => x.IsActivate && x.IsGps).ToList(); + } + + //gps车辆数据 + List gpsRealTimes = await _gpsRealTimeRepository.GetGpsRealTimeByCompanyId(_userManager.CompanyId); + //车辆列表 + //List vehicles = (await _cacheService.GetVehicleByCompanyIdAsync(_userManager.CompanyId)).Where(x => x.IsActivate && x.IsGps).ToList(); + + List vehicleGpsOutputsList = new List(); + foreach (VehicleGpsOutput vehicle in vehicles) + { + GpsRealTime gpsRealTime = gpsRealTimes.FirstOrDefault(x => x.VehicleId == vehicle.Id); + VehicleGpsOutput vehicleGpsOutput = new VehicleGpsOutput + { + Id = vehicle.Id, + VehiclePlate = vehicle.VehiclePlate, + VehicleCode = vehicle.VehicleCode, + Status = vehicle.Status, + CompanyId = vehicle.CompanyId, + Speed = gpsRealTime?.Speed ?? 0, + GpsState = gpsRealTime?.GpsState ?? 0, + AccDurationTime = gpsRealTime?.AccDurationTime ?? "0分钟", + DurationTime = gpsRealTime?.DurationTime ?? "0分钟", + OfflineTime = + gpsRealTime.IsNull() || gpsRealTime?.RecTime < Convert.ToDateTime("2000-01-01 00:00:00.000") + ? "未激活" + : StringHelper.ShowTimeInterval(gpsRealTime?.RecTime.AddHours(8)), + GpsTime = gpsRealTime.IsNull() || + gpsRealTime?.GpsTime < Convert.ToDateTime("2000-01-01 00:00:00.000") + ? "2000-01-01 00:00:00.000" + : gpsRealTime?.GpsTime.ToString("yyyy-MM-dd HH:mm-ss"), + ContactPerson = vehicle.ContactPerson, + ContactPhone = vehicle.ContactPhone, + Address = gpsRealTime.IsNull() || gpsRealTime.Address.IsNull() ? "暂无位置" : gpsRealTime?.Address, + + }; + vehicleGpsOutputsList.Add(vehicleGpsOutput); + } + + int allCount = vehicleGpsOutputsList.Count; + int stillCount = vehicleGpsOutputsList.Count(x => x.GpsState == (int)GpsStatusEnum.STILL); + int drivingCount = vehicleGpsOutputsList.Count(x => x.GpsState == (int)GpsStatusEnum.DRIVING); + int offlineCount = vehicleGpsOutputsList.Count(x => x.GpsState == (int)GpsStatusEnum.OFFLINE); + VehicleListOutput result = new VehicleListOutput + { + vehicleGpsOutput = vehicleGpsOutputsList + .WhereIf(status > -1, x => x.GpsState == status) + .WhereIf(key.IsNotEmptyOrNull(), x => x.VehicleCode.Contains(key) || x.VehiclePlate.Contains(key)) + .OrderBy(x => x.VehicleCode) + .Skip((currentPage - 1) * pageSize) + .Take(pageSize) + .ToList(), + AllCount = allCount, + StillCount = stillCount, + DrivingCount = drivingCount, + OfflineCount = offlineCount + }; + return result; + } + + /// + /// 修改车辆信息 + /// + /// + /// + [HttpPut] + [Route("api/v1/vehicle")] + public async Task UpdateAsync(VehicleUpdateInput input) + { + await _repository.UpdateIncludeNowAsync(input.Adapt(), + new[] + { + nameof(Vehicle.VehicleCode), nameof(Vehicle.VehiclePlate), nameof(Vehicle.ContactPerson), + nameof(Vehicle.ContactPhone) + }, + true); + //同步修改油耗表设备号 + await "update dc_oil set VehicleCode=@vehicleCode where VehicleId=@id And IsDeleted=0".SqlNonQueryAsync(new { id = input.Id, vehicleCode = input.VehicleCode }); + //同步修改订单表设备号 + await "update dc_order set VehicleCode=@vehicleCode where VehicleId=@id And IsDeleted=0".SqlNonQueryAsync(new { id = input.Id, vehicleCode = input.VehicleCode }); + + await _cacheService.RemoveVehicleAsync(input.Id); + await _cacheService.RemoveVehicleByCompanyIdAsync(_userManager.CompanyId); + } + + /// + /// 轨迹回放纠偏 + /// + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/trackplayback")] + public async Task TrackPlaybackCorrectionAsync(long vehicleId, DateTime startTime, + DateTime endTime) + { + //查询Cache + TrackPlaybackListOutput trackPlaybackListOutput = await _cacheService.GetTrackPlaybackAsync(vehicleId, startTime, endTime); + if (trackPlaybackListOutput.IsNull()) + { + //返回轨迹实体 + List reult = new List(); + //公司数据 + CompanyOutput company = await _cacheService.GetCompanyAsync(_userManager.CompanyId, _userManager.UserId); + //车辆 + Vehicle vehicle = await _cacheService.GetVehicleAsync(vehicleId); + //停留标示数据 + int stopTag = (await _dictionaryService.GetAsync(company.StopTag)).Value.ToInt(); + //车辆行驶记录 + List list = await FindGpsByTime(vehicleId, startTime, endTime); + //过滤数据 + List finalGpsList = GpsDataProcessing(list); //处理数据 + + //纠偏后数据 + List newFinalGpsList = new List(); //处理数据 + + List stopList = new List(); + + TimeSpan stopTimeSpan = new TimeSpan(); + if (finalGpsList.Count < 30) + { + throw Oops.Oh("暂无轨迹"); + } + int firstGpsTime = finalGpsList[0].GpsTime.ToTimestamp(); + List rectifyList = finalGpsList.Select(x => new TrackPlayBackCorrectInput + { + Longitude = x.Longitude.ToString("f6").ToDecimal(), + Latitude = x.Latitude.ToString("f6").ToDecimal(), + Direct = x.Direct, + Timestamp = x.GpsTime.ToTimestamp() > firstGpsTime ? x.GpsTime.ToTimestamp() - firstGpsTime : firstGpsTime, + Speed = x.Speed + }).ToList(); + string c = JsonConvert.SerializeObject(rectifyList); + List rectifyOutput = new List(); + int size = 500; + //原始轨迹点 + int reultCount = finalGpsList.Count; + int integerCount = (int)Math.Ceiling((decimal)reultCount / size); + + for (int i = 0; i < integerCount; i++) + { + TrackPlayBackCorrectOutput res = JsonConvert.DeserializeObject(HttpRequestHelper.HttpPost("https://restapi.amap.com/v4/grasproad/driving?key=89981abaf32ae94b09a639c54845e089", + rectifyList.Skip(i * size).Take(size))); + if (res.ErrCode == 0) + { + + rectifyOutput.AddRange(res.data.points.ToList()); + } + else + { + List residuePoints = rectifyList.Skip(i * size).Select(x => new Points + { + Latitude = x.Latitude, + Longitude = x.Longitude + }).ToList(); + rectifyOutput.AddRange(residuePoints); + } + } + + decimal totalDistance = 0;//总里程 + int totalPoints = rectifyOutput.Count;//纠偏后的点总数 + float index = (float)totalPoints / finalGpsList.Count; + int multiple = totalPoints % finalGpsList.Count == 0 ? totalPoints / finalGpsList.Count : totalPoints / finalGpsList.Count + 1; + for (int i = 0; i < rectifyOutput.Count; i++) + { + TrackPlaybackOutput output = new TrackPlaybackOutput(); + int k = (int)Math.Round(i / index); + if (k >= finalGpsList.Count) + { + k = finalGpsList.Count - 1; + } + VehicleGps gps = finalGpsList[k]; + gps.Longitude = rectifyOutput[i].Longitude; + gps.Latitude = rectifyOutput[i].Latitude; + gps.Speed = gps.Speed == 0 ? 21 : gps.Speed; + newFinalGpsList.Add(gps); + } + #region 计算停留点 + int stopIdx = 0; + VehicleGps firstGps = new VehicleGps(); + newFinalGpsList = newFinalGpsList.Distinct().ToList(); + for (int i = 0; i < newFinalGpsList.Count; i++) + { + TrackPlaybackOutput output = new TrackPlaybackOutput(); + VehicleGps gps = newFinalGpsList[i]; + output.Longitude = gps.Longitude; + output.Latitude = gps.Latitude; + output.GpsTime = gps.GpsTime.AddHours(8); + output.StartTime = gps.GpsTime.AddHours(8); + output.EndTime = gps.GpsTime.AddHours(8); + output.Speed = gps.Speed; + output.Direct = gps.Direct; + output.DurationTime = ""; + output.IsStopPoint = false; + output.StopPointIdx = -1; + output.Address = gps.Address; + output.Acc = gps.Acc; + output.AccDurationTime = ""; + output.Work = gps.Work; + output.WorkDurationTime = ""; + output.TotalDistance = 0; + if (i != 0) + { + VehicleGps preGps = newFinalGpsList[i - 1]; + totalDistance += DistanceHelper.GetDistance(Convert.ToDouble(gps.Latitude), + Convert.ToDouble(gps.Longitude), + Convert.ToDouble(preGps.Latitude), Convert.ToDouble(preGps.Longitude)); + output.TotalDistance = totalDistance; + //用于计算停留点 + if (gps.GpsTime.ConvertToTimestamp() - preGps.GpsTime.ConvertToTimestamp() > 300) + { + string durationTime = TimeHelper.TimeSpanFormat(gps.GpsTime - preGps.GpsTime, 3); + string address = MapHelper.GetLocationByLngLat(reult.LastOrDefault().Longitude, + reult.LastOrDefault().Latitude); + //停留点 + reult.LastOrDefault().DurationTime = durationTime; + if (firstGps.GpsTime.ConvertToTimestamp() != preGps.GpsTime.ConvertToTimestamp()) + { + reult.LastOrDefault().StopPointIdx = ++stopIdx; + reult.LastOrDefault().IsStopPoint = true; + } + reult.LastOrDefault().Address = address; + reult.LastOrDefault().StartTime = preGps.GpsTime.AddHours(8); + reult.LastOrDefault().EndTime = gps.GpsTime.AddHours(8); + stopTimeSpan += (gps.GpsTime - preGps.GpsTime); + //如果第一点是停留点,则将停留时间更新到第一个点上 + if (firstGps.GpsTime == preGps.GpsTime) + { + stopList.LastOrDefault().Behavior = "停留" + durationTime; + } + else + { + //停留点插入轨迹动态列表 + Stop stop = new Stop(); + stop.GpsTime = preGps.GpsTime.AddHours(8); + stop.Latitude = preGps.Latitude; + stop.Longitude = preGps.Longitude; + stop.Address = address; + stop.State = "停" + stopIdx; + stop.Status = 1; + stop.Behavior = "停留" + durationTime; + stop.TotalDistance = totalDistance != 0 ? totalDistance : 0; + stop.StartTime = preGps.GpsTime; + stop.EndTime = output.GpsTime; + stopList.Add(stop); + } + } + if (i == newFinalGpsList.Count - 1) + { + Stop stop = new Stop(); + VehicleGps lastGps = newFinalGpsList[i]; + string address = lastGps.Address; + output.Address = address; + stop.Latitude = lastGps.Latitude; + stop.Longitude = lastGps.Longitude; + stop.GpsTime = lastGps.GpsTime.AddHours(8); + stop.Address = lastGps.Address; + stop.State = "终点"; + stop.Status = 3; + stop.Behavior = ""; + stop.TotalDistance = totalDistance != 0 ? totalDistance : 0; + stopList.Add(stop); + } + } + else + { + firstGps = newFinalGpsList[0]; + string address = firstGps.Address; + Stop stop = new Stop + { + Latitude = firstGps.Latitude, + Longitude = firstGps.Longitude, + GpsTime = firstGps.GpsTime.AddHours(8), + Address = address, + State = "起点", + Status = 0, + Behavior = "", + TotalDistance = 0 + }; + stopList.Add(stop); + output.Address = address; + } + if (newFinalGpsList.Count == 1) + { + firstGps = newFinalGpsList[0]; + string address = firstGps.Address; + Stop stop = new Stop(); + stop.Latitude = firstGps.Latitude; + stop.Longitude = firstGps.Longitude; + stop.GpsTime = endTime; + stop.Address = address; + stop.State = "终点"; + stop.Status = 3; + stop.Behavior = ""; + stop.TotalDistance = 0; + stopList.Add(stop); + } + reult.Add(output); + } + #endregion 计算停留点 + + trackPlaybackListOutput = new TrackPlaybackListOutput + { + VehicleCode = vehicle.VehicleCode, + VehiclePlate = vehicle.VehiclePlate, + TotalDistance = totalDistance != 0 ? totalDistance : 0, + TotalStopTime = TimeHelper.TimeSpanFormat(stopTimeSpan, 3), + trackPlaybackOutputs = reult, + Stops = stopList + }; + //若查询时间包含今天,缓存录入10分钟 + TimeSpan expire = DateTimeHelper.IsToday(endTime) ? expire = TimeSpan.FromMinutes(15) : TimeSpan.FromDays(7); + await _cacheService.SeTrackPlaybackAsync(trackPlaybackListOutput, vehicleId, startTime, endTime, expire); + } + return trackPlaybackListOutput; + } + + /// + /// 修改超速报警/速度 + /// + /// + /// + /// + /// + [HttpPut] + [Route("api/v1/vehicle/overspeed/{vehicleId}/{isOverspeedAlarm}/{overSpeed}")] + + public async Task UpdateOverSpeedAsync(long vehicleId, bool isOverspeedAlarm, [DataValidation(ValidationTypes.PositiveNumber, ErrorMessage = "超速报警时速必须为数字")] int overSpeed) + { + Vehicle vehicle = await _cacheService.GetVehicleAsync(vehicleId); + vehicle.Overspeed = overSpeed; + vehicle.IsOverspeedAlarm = isOverspeedAlarm; + await _repository.UpdateIncludeNowAsync(vehicle, + new[] { nameof(Vehicle.IsOverspeedAlarm), nameof(Vehicle.Overspeed) }, true); + await _cacheService.RemoveVehicleAsync(vehicleId); + await _cacheService.RemoveVehicleByCompanyIdAsync(_userManager.CompanyId); + return true; + } + + /// + /// 超速报警列表 + /// + /// + /// + /// + [HttpGet] + [UnitOfWork] + [Route("api/v1/vehicles/alertspeeds/{currentPage}/{pageSize}")] + public async Task MbAlertSpeedByTime([Required] int currentPage = 1, + [Required] int pageSize = 10) + { + List vehicleList = await _cacheService.GetVehicleByCompanyIdAsync(_userManager.CompanyId); + if (vehicleList.IsNull() || vehicleList.Count() <= 0) + { + throw Oops.Oh("暂无超速记录"); + } + List alarmList = await _pgyAlertStraightGtlRepository.FindAlarmPageAsync(_userManager.CompanyId, currentPage, pageSize); + List list = alarmList + .Select(x => new PgyAlertStraightDtlOutput + { + VehicleId = vehicleList.Where(v => v.VehicleCode == x.VehicleCode && v.VehiclePlate == x.VehiclePlate).FirstOrDefault().Id, + CompanyId = x.CompanyId, + VehicleCode = x.VehicleCode, + VehiclePlate = x.VehiclePlate, + GpsTime = x.GpsTime.AddHours(8), + Latitude = x.Latitude, + Longitude = x.Longitude, + Direct = x.Direct, + Speed = x.Speed, + Address = x.Address + }) + .ToList(); + PgyAlertStraightDtlListOutput result = new PgyAlertStraightDtlListOutput() + { + TotalCount = (await _pgyAlertStraightGtlRepository.FindAlarmCountAsync(_userManager.CompanyId)).ToInt(), + List = list + }; + await _cacheService.SetUnreadAlarmAsync(_userManager.UserId); + return result; + } + + /// + /// 未读报警消息数 + /// + /// + [HttpGet] + [Route("api/v1/unreadalarm")] + + public async Task UnreadAlarmCountAsync() + { + DateTime readTime = await _cacheService.GetUnreadAlarmAsync(_userManager.UserId); + if (readTime.IsNull() || readTime == Convert.ToDateTime("0001-01-01 00:00:00.000")) + { + readTime = DateTime.Now.Date; + } + + IQueryable vehicleList = _repository.DetachedEntities + .Where(x => x.IsOverspeedAlarm == true && x.CompanyId == _userManager.CompanyId + && x.Status == (int)CommonStatusEnum.ENABLE); + AlarmOutput result = new AlarmOutput(); + if (vehicleList.IsNull() || !vehicleList.Any()) + { + return result; + } + List alarmList = await _pgyAlertStraightGtlRepository.FindAlarmListByTime(_userManager.CompanyId); + if (alarmList.IsNull()) + { + return result; + } + alarmList = alarmList.OrderByDescending(x => x.GpsTime).ToList(); + result.OverspeedCount = alarmList.Count(x => x.GpsTime > readTime); + result.OverspeedTime = alarmList.FirstOrDefault()?.GpsTime.AddHours(8); + result.VehicleCode = alarmList.FirstOrDefault()?.VehicleCode; + result.VehiclePlate = alarmList.FirstOrDefault()?.VehiclePlate; + return result; + } + + /// + /// 获取车辆GPS信息 + /// + /// 车辆Id + /// 开始时间 + /// 结束时间 + /// + private async Task> FindGpsByTime(long vehicleId, DateTime startTime, DateTime endTime) + { + string smon = startTime.ToString("MM"); + string emon = endTime.ToString("MM"); + string syear = startTime.ToString("yyyyMM"); + string eyear = endTime.ToString("yyyyMM"); + List list = new List(); + if (smon == emon) + { + FilterDefinition filter = Builders.Filter.Gte("GpsTime", startTime) & + Builders.Filter.Lt("GpsTime", endTime) & + Builders.Filter.Eq("Acc", 1); + string tbName = "Car_" + vehicleId + "_" + syear; + list = await _mongodbBaseRepository.GetVehicleGpsListAsync(tbName, filter); + } + else + { + //取开始时间到次月第一天 + DateTime etimeone = DateTime.Parse(startTime.AddMonths(1).ToString("yyyy-MM-01")); //次月第一天 + FilterDefinition filter1 = Builders.Filter.Gt("GpsTime", startTime) & + Builders.Filter.Lte("GpsTime", etimeone) & + Builders.Filter.Eq("Acc", 1); + string tbName1 = "Car_" + vehicleId + "_" + syear; + List list1 = await _mongodbBaseRepository.GetVehicleGpsListAsync(tbName1, filter1); + + //取结束时间月份第一天到结束时间 + DateTime etimetwo = DateTime.Parse(endTime.ToString("yyyy-MM-01")); //结束月份第一天 + FilterDefinition filter2 = Builders.Filter.Gt("GpsTime", etimetwo) & + Builders.Filter.Lte("GpsTime", endTime) & + Builders.Filter.Eq("Acc", 1); + string tbName2 = "Car_" + vehicleId + "_" + eyear; + List list2 = await _mongodbBaseRepository.GetVehicleGpsListAsync(tbName2, filter2); + list.AddRange(list1); + list.AddRange(list2); + } + return list.Count > 0 ? list : new List(); + } + + /// + /// 轨迹点预处理(车辆) + /// + /// + /// + private List GpsDataProcessing(List list) + { + List carGpsList = new List(); + int moveDistance = 40; + //轨迹点数小于10个, 则提示暂无轨迹 + if (list.Count < 20) + { + return new List(); + } + //判断前五个点是否正常 + for (int i = 0; i < 5; i++) + { + List firstToTenGps = new List(); + + for (int j = 0; j < 10 - i; j++) + { + VehicleGps model = list[j]; + firstToTenGps.Add(model); + } + + if (!firstToTenGps.Any()) + { + continue; + } + { + //平均经纬度 + double avgLat = Convert.ToDouble(firstToTenGps.Average(x => x.Latitude)); + double avgLng = Convert.ToDouble(firstToTenGps.Average(x => x.Longitude)); + //所有点距离 + List distanceList = + firstToTenGps.Select( + model => + Convert.ToDouble(DistanceHelper.GetDistance(avgLat, avgLng, + Convert.ToDouble(model.Latitude), + Convert.ToDouble(model.Longitude))) * 1000).ToList(); + //找出最大值的位置 + double max = distanceList.Max(); + int maxIndex = distanceList.IndexOf(max); + //最大值是否是第一个点, 以及距离大于625米, 150 km/h 乘 15秒 + if (maxIndex == 0 && max > 625) + { + list.Remove(list.FirstOrDefault()); + } + else + { + break; + } + } + } + + //去掉太远的点 + VehicleGps preGps = null; + foreach (VehicleGps model in list) + { + if (preGps != null) + { + decimal distance = DistanceHelper.GetDistance((double)preGps.Latitude, (double)preGps.Longitude, + (double)model.Latitude, (double)model.Longitude) * 1000; + long ts = model.GpsTime.ConvertToTimestamp() - preGps.GpsTime.ConvertToTimestamp(); + if (distance > 0 && distance < 50 * 1000) + { + if (distance < (decimal)(150 / 3.6 * ts)) + { + carGpsList.Add(model); + preGps = model; + } + } + } + else + { + carGpsList.Add(model); + preGps = model; + } + } + List finalGpsList = new List(); //处理完后的最终集合 + + //去掉距离太近的点, 去重 + preGps = null; + foreach (VehicleGps gps in carGpsList) + { + if (preGps != null) + { + decimal distance = DistanceHelper.GetDistance((double)preGps.Latitude, (double)preGps.Longitude, + (double)gps.Latitude, (double)gps.Longitude) * 1000; + if (distance > moveDistance) + { + finalGpsList.Add(gps); + preGps = gps; + } + } + else + { + finalGpsList.Add(gps); + preGps = gps; + } + } + + return carGpsList; + } + + + /// + /// 离线车辆报警 + /// + /// + [HttpGet] + public async Task VehicleOfflineAsync() + { + List gpsRealTimeList = await _gpsRealTimeRepository.GetOfflineGpsRealTime(); + foreach (GpsRealTime item in gpsRealTimeList) + { + IQueryable users = from e in _employeeRepository.Where(x => + x.CompanyId == item.CompanyId && x.RoleId == 1 && x.Status == (int)CommonStatusEnum.ENABLE) + .AsQueryable() + join u in _userRepository.Where(x => x.Status == CommonStatusEnum.ENABLE).AsQueryable() + on e.UserId equals u.Id + select new NoticeOutput + { + OpenId = u.OpenId + }; + foreach (NoticeOutput i in users) + { + // WxUserRelation wxUserRelation = await _wxUserRelationRepository.DetachedEntities + // .Where(x => x.OpenId == i.OpenId).FirstOrDefaultAsync(); + // if (wxUserRelation.WxOfficialOpenId.IsNotNull()) + // { + // WeixinTemplate_OfflineNotice data = new WeixinTemplate_OfflineNotice("尊敬的用户,你的车辆已离线", + // item.VehicleCode, item.VehiclePlate, item.Address); + // AccessTokenResult accessTokenResult = await CommonApi.GetTokenAsync(App.Configuration["SenparcWeixinSetting:WeixinAppId"], + // App.Configuration["SenparcWeixinSetting:WeixinAppSecret"]); + // SendTemplateMessageResult result = await TemplateApi.SendTemplateMessageAsync(accessTokenResult.access_token, + // wxUserRelation.WxOfficialOpenId, data.TemplateId, "", data); + // } + } + } + + return true; + } + + + #region 轨迹 + + /// + /// 同步轨迹 + /// + /// + [HttpGet] + [AllowAnonymous] + public async Task SyncTrackPlaybackCorrectionAsync(DateTime startTime, DateTime endTime, string type) + { + List vehicles = await _repository.Where(x => x.Status == (int)CommonStatusEnum.ENABLE && x.IsGps == true && x.IsActivate == true).ToListAsync(); + foreach (Vehicle vehicle in vehicles) + { + await SetTrackPlaybackCorrectionAsync(vehicle.Id, vehicle.CompanyId, startTime, endTime, type); + } + } + + /// + /// 轨迹回放纠偏 + /// + /// + /// + /// + /// + /// + /// + private async Task SetTrackPlaybackCorrectionAsync(long vehicleId, long companyId, DateTime startTime, DateTime endTime, string type) + { + //查询Cache + TrackPlaybackListOutput trackPlaybackListOutput = new TrackPlaybackListOutput(); + + //返回轨迹实体 + List reult = new List(); + //公司数据 + CompanyOutput company = await _cacheService.GetCompanyAsync(companyId, _userManager.UserId); + //车辆 + Vehicle vehicle = await _cacheService.GetVehicleAsync(vehicleId); + //停留标示数据 + int stopTag = (await _dictionaryService.GetAsync(company.StopTag)).Value.ToInt(); + //车辆行驶记录 + List list = await FindGpsByTime(vehicleId, startTime, endTime); + //过滤数据 + Console.WriteLine(startTime); Console.WriteLine(endTime); + + List finalGpsList = GpsDataProcessing(list); //处理数据 + + //纠偏后数据 + List newFinalGpsList = new List(); //处理数据 + + List stopList = new List(); + + TimeSpan stopTimeSpan = new TimeSpan(); + if (finalGpsList.Count < 30) + { + return; + } + int firstGpsTime = finalGpsList[0].GpsTime.ToTimestamp(); + List rectifyList = finalGpsList.Select(x => new TrackPlayBackCorrectInput + { + Longitude = x.Longitude.ToString("f6").ToDecimal(), + Latitude = x.Latitude.ToString("f6").ToDecimal(), + Direct = x.Direct, + Timestamp = x.GpsTime.ToTimestamp() > firstGpsTime ? x.GpsTime.ToTimestamp() - firstGpsTime : firstGpsTime, + Speed = x.Speed + }).ToList(); + string c = JsonConvert.SerializeObject(rectifyList); + List rectifyOutput = new List(); + int size = 500; + //原始轨迹点 + int reultCount = finalGpsList.Count; + int integerCount = (int)Math.Ceiling((decimal)reultCount / size); + + for (int i = 0; i < integerCount; i++) + { + TrackPlayBackCorrectOutput res = JsonConvert.DeserializeObject(HttpRequestHelper.HttpPost("https://restapi.amap.com/v4/grasproad/driving?key=89981abaf32ae94b09a639c54845e089", + rectifyList.Skip(i * size).Take(size))); + if (res.ErrCode == 0) + { + + rectifyOutput.AddRange(res.data.points.ToList()); + } + else + { + List residuePoints = rectifyList.Skip(i * size).Select(x => new Points + { + Latitude = x.Latitude, + Longitude = x.Longitude + }).ToList(); + rectifyOutput.AddRange(residuePoints); + } + } + + decimal totalDistance = 0;//总里程 + int totalPoints = rectifyOutput.Count;//纠偏后的点总数 + float index = (float)totalPoints / finalGpsList.Count; + int multiple = totalPoints % finalGpsList.Count == 0 ? totalPoints / finalGpsList.Count : totalPoints / finalGpsList.Count + 1; + for (int i = 0; i < rectifyOutput.Count; i++) + { + TrackPlaybackOutput output = new TrackPlaybackOutput(); + int k = (int)Math.Round(i / index); + if (k >= finalGpsList.Count) + { + k = finalGpsList.Count - 1; + } + VehicleGps gps = finalGpsList[k]; + gps.Longitude = rectifyOutput[i].Longitude; + gps.Latitude = rectifyOutput[i].Latitude; + gps.Speed = gps.Speed == 0 ? 21 : gps.Speed; + newFinalGpsList.Add(gps); + } + #region 计算停留点 + int stopIdx = 0; + VehicleGps firstGps = new VehicleGps(); + newFinalGpsList = newFinalGpsList.Distinct().ToList(); + for (int i = 0; i < newFinalGpsList.Count; i++) + { + TrackPlaybackOutput output = new TrackPlaybackOutput(); + VehicleGps gps = newFinalGpsList[i]; + output.Longitude = gps.Longitude; + output.Latitude = gps.Latitude; + output.GpsTime = gps.GpsTime.AddHours(8); + output.StartTime = gps.GpsTime.AddHours(8); + output.EndTime = gps.GpsTime.AddHours(8); + output.Speed = gps.Speed; + output.Direct = gps.Direct; + output.DurationTime = ""; + output.IsStopPoint = false; + output.StopPointIdx = -1; + output.Address = gps.Address; + output.Acc = gps.Acc; + output.AccDurationTime = ""; + output.Work = gps.Work; + output.WorkDurationTime = ""; + output.TotalDistance = 0; + if (i != 0) + { + VehicleGps preGps = newFinalGpsList[i - 1]; + totalDistance += DistanceHelper.GetDistance(Convert.ToDouble(gps.Latitude), + Convert.ToDouble(gps.Longitude), + Convert.ToDouble(preGps.Latitude), Convert.ToDouble(preGps.Longitude)); + output.TotalDistance = totalDistance; + //用于计算停留点 + if (gps.GpsTime.ConvertToTimestamp() - preGps.GpsTime.ConvertToTimestamp() > 300) + { + string durationTime = TimeHelper.TimeSpanFormat(gps.GpsTime - preGps.GpsTime, 3); + string address = MapHelper.GetLocationByLngLat(reult.LastOrDefault().Longitude, + reult.LastOrDefault().Latitude); + //停留点 + reult.LastOrDefault().DurationTime = durationTime; + if (firstGps.GpsTime.ConvertToTimestamp() != preGps.GpsTime.ConvertToTimestamp()) + { + reult.LastOrDefault().StopPointIdx = ++stopIdx; + reult.LastOrDefault().IsStopPoint = true; + } + reult.LastOrDefault().Address = address; + reult.LastOrDefault().StartTime = preGps.GpsTime.AddHours(8); + reult.LastOrDefault().EndTime = gps.GpsTime.AddHours(8); + stopTimeSpan += (gps.GpsTime - preGps.GpsTime); + //如果第一点是停留点,则将停留时间更新到第一个点上 + if (firstGps.GpsTime == preGps.GpsTime) + { + stopList.LastOrDefault().Behavior = "停留" + durationTime; + } + else + { + //停留点插入轨迹动态列表 + Stop stop = new Stop(); + stop.GpsTime = preGps.GpsTime.AddHours(8); + stop.Latitude = preGps.Latitude; + stop.Longitude = preGps.Longitude; + stop.Address = address; + stop.State = "停" + stopIdx; + stop.Status = 1; + stop.Behavior = "停留" + durationTime; + stop.TotalDistance = totalDistance != 0 ? totalDistance : 0; + stop.StartTime = preGps.GpsTime; + stop.EndTime = output.GpsTime; + stopList.Add(stop); + } + } + if (i == newFinalGpsList.Count - 1) + { + Stop stop = new Stop(); + VehicleGps lastGps = newFinalGpsList[i]; + string address = lastGps.Address; + output.Address = address; + stop.Latitude = lastGps.Latitude; + stop.Longitude = lastGps.Longitude; + stop.GpsTime = lastGps.GpsTime.AddHours(8); + stop.Address = lastGps.Address; + stop.State = "终点"; + stop.Status = 3; + stop.Behavior = ""; + stop.TotalDistance = totalDistance != 0 ? totalDistance : 0; + stopList.Add(stop); + } + } + else + { + firstGps = newFinalGpsList[0]; + string address = firstGps.Address; + Stop stop = new Stop + { + Latitude = firstGps.Latitude, + Longitude = firstGps.Longitude, + GpsTime = firstGps.GpsTime.AddHours(8), + Address = address, + State = "起点", + Status = 0, + Behavior = "", + TotalDistance = 0 + }; + stopList.Add(stop); + output.Address = address; + } + if (newFinalGpsList.Count == 1) + { + firstGps = newFinalGpsList[0]; + string address = firstGps.Address; + Stop stop = new Stop(); + stop.Latitude = firstGps.Latitude; + stop.Longitude = firstGps.Longitude; + stop.GpsTime = endTime; + stop.Address = address; + stop.State = "终点"; + stop.Status = 3; + stop.Behavior = ""; + stop.TotalDistance = 0; + stopList.Add(stop); + } + reult.Add(output); + } + #endregion 计算停留点 + + trackPlaybackListOutput = new TrackPlaybackListOutput + { + VehicleCode = vehicle.VehicleCode, + VehiclePlate = vehicle.VehiclePlate, + TotalDistance = totalDistance != 0 ? totalDistance : 0, + TotalStopTime = TimeHelper.TimeSpanFormat(stopTimeSpan, 3), + trackPlaybackOutputs = reult, + Stops = stopList + }; + + + + TimeSpan timeSpan = type == "Today" ? TimeSpan.FromMinutes(10) : TimeSpan.FromDays(3); + await _cacheService.SeTrackPlaybackAsync(trackPlaybackListOutput, vehicleId, startTime, endTime, timeSpan); + } + #endregion + + #region v1.2.1 + /// + /// 基础数据-车辆管理列表 + /// + /// + /// + /// + /// 0全部,停用-1,正常1 + /// + [HttpGet] + [Route("api/v1/basics/vehicles/search")] + public async Task BasicsPageAsync([Required] int currentPage, [Required] int pageSize, [FromQuery] int status, [FromQuery] string key) + { + var vehicleGpsList = (await _cacheService.GetVehicleByCompanyIdAsync(_userManager.CompanyId)) + .WhereIf(status > 0, x => x.Status == status) + .WhereIf(key.IsNotEmptyOrNull(), x => x.VehicleCode.Contains(key)).Adapt>(); + foreach (var item in vehicleGpsList) + { + item.VehiclePerson = await _cacheService.GetVehiclePersonAsync(item.Id); + item.VehiclePersonName = item.VehiclePerson.Find(x => x.IsDriver == true)?.UserName; + item.VehiclePersonPhone = item.VehiclePerson.Find(x => x.IsDriver == true)?.UserPhone; + } + var vehicleOutputs = new List(); + foreach (var INDEX_STRING in INDEX_STRINGS) + { + vehicleOutputs.Add(new VehicleBaiscListOutputs() + { + Char = INDEX_STRING, + List = vehicleGpsList.Where(x => StringHelper.GetStringFirstSpell(x.VehicleCode) == INDEX_STRING).ToList() + }); + }; + var data = new VehicleBaiscListPage() + { + VehicleBaiscList = vehicleOutputs, + Total = vehicleGpsList.Count + }; + return data; + } + + /// + /// 基础数据-车辆信息 + /// + /// + /// + [HttpGet] + [Route("api/v1/basics/vehicle/{vehicleId}")] + public async Task GetVehicleBasicsByIdAsync(long vehicleId) + { + //车辆 + Vehicle vehicle = await _cacheService.GetVehicleAsync(vehicleId); + if (vehicle.IsNull()) + { + Oops.Oh("暂无车辆信息"); + } + VehicleBaiscListOutput VehicleBaisc = vehicle.Adapt(); + VehicleBaisc.VehiclePerson = await _cacheService.GetVehiclePersonAsync(vehicleId); + return VehicleBaisc; + } + + /// + /// 更新车辆基础信息 + /// + /// + /// + [UnitOfWork] + [HttpPut] + [Route("api/v1/basics/vehicle")] + public async Task BasicsUpdateAsync(BasicsVehicleUpdateInput input) + { + var vehicle = await _repository.FirstOrDefaultAsync(x => x.Id == input.Id); + if (vehicle.IsNull()) throw Oops.Oh("暂无该信息"); + var repeatVehicle = await _repository.DetachedEntities + .Where(x => x.Id != input.Id && ((x.VehicleCode == input.VehicleCode && x.CompanyId == _userManager.CompanyId) || + (x.VehiclePlate == input.VehiclePlate && x.Status == (int)CommonStatusEnum.ENABLE))) + .FirstOrDefaultAsync(); + if (repeatVehicle.IsNotNull()) + { + throw Oops.Bah("车牌号或设备名称重复"); + } + //车组人员人数无上限,至少存在一个司机才可保存 + if (input.VehiclePersons.Count > 0) + { + var isDriver = input.VehiclePersons.Find(x => x.IsDriver == true); + if (isDriver.IsNull()) + { + throw Oops.Bah("车组人员至少需要一个司机"); + } + } + + #region 修改车组人员 + var oldVehiclePersons = await _vehiclePersonRepository.DetachedEntities + .Where(x => x.VehicleId == input.Id && x.IsDeleted == false) + .ToListAsync(); + var oldVehiclePersonIds = oldVehiclePersons.IsNotNull() ? oldVehiclePersons.Select(x => x.UserId).ToArray() : new long[] { }; + var newVehiclePersonIds = input.VehiclePersons.IsNotNull() ? input.VehiclePersons.Select(x => x.UserId).ToArray() : new long[] { }; + var deleteVehiclePersonIds = oldVehiclePersonIds.Except(newVehiclePersonIds).ToArray(); + if (deleteVehiclePersonIds.Length > 0) + { + for (int i = 0; i < deleteVehiclePersonIds.Length; i++) + { + var vehiclePerson = oldVehiclePersons.FirstOrDefault(x => x.UserId == deleteVehiclePersonIds[i]); + vehiclePerson.IsDeleted = true; + await _vehiclePersonRepository.UpdateNowAsync(vehiclePerson); + } + } + if (input.VehiclePersons.IsNotNull()) + { + foreach (var item in input.VehiclePersons) + { + var oldvehiclePerson = oldVehiclePersons.Find(x => x.UserId == item.UserId); + if (oldvehiclePerson.IsNull()) + { + var vehiclePerson = item.Adapt(); + vehiclePerson.VehicleId = input.Id; + await _vehiclePersonRepository.InsertNowAsync(vehiclePerson); + } + else + { + var vehiclePerson = item.Adapt(); + vehiclePerson.Id = oldvehiclePerson.Id; + await _vehiclePersonRepository.UpdateNowAsync(vehiclePerson); + } + } + } + + #endregion + + var result = await _repository.UpdateNowAsync(input.Adapt(vehicle)); + if (result.IsNull()) + { + throw Oops.Oh("修改车辆基础信息失败"); + } + + //同步修改油耗表和订单表设备号 + if (input.VehicleCode != vehicle.VehicleCode) + { + //油耗表 + await "update dc_oil set VehicleCode=@vehicleCode where VehicleId=@id And IsDeleted=0".SqlNonQueryAsync(new { id = input.Id, vehicleCode = input.VehicleCode }); + //订单表 + await "update dc_order set VehicleCode=@vehicleCode where VehicleId=@id And IsDeleted=0".SqlNonQueryAsync(new { id = input.Id, vehicleCode = input.VehicleCode }); + } + await _cacheService.RemoveVehiclePersonAsync(input.Id); + await _cacheService.RemoveVehicleAsync(input.Id); + await _cacheService.RemoveVehicleByCompanyIdAsync(_userManager.CompanyId); + } + #endregion + + + } + +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehicleGroup/Dto/Input/VehicleGroupAddInput.cs b/src/Znyc.Dispatching.Application/VehicleGroup/Dto/Input/VehicleGroupAddInput.cs new file mode 100644 index 0000000..d24707b --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehicleGroup/Dto/Input/VehicleGroupAddInput.cs @@ -0,0 +1,20 @@ +namespace Znyc.Dispatching.Application +{ + public class VehicleGroupAddInput + { + /// + /// 公司Id + /// + public long CompanyId { get; set; } + + /// + /// 名称 + /// + public string Name { get; set; } + + /// + /// 父级权限Id + /// + public long ParentId { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehicleGroup/Dto/OutPut/VehicleGroupOutput.cs b/src/Znyc.Dispatching.Application/VehicleGroup/Dto/OutPut/VehicleGroupOutput.cs new file mode 100644 index 0000000..c2659bc --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehicleGroup/Dto/OutPut/VehicleGroupOutput.cs @@ -0,0 +1,32 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class VehicleGroupOutput + { + /// + /// Id + /// + public long Id { get; set; } + + /// + /// 公司Id + /// + public long CompanyId { get; set; } + + /// + /// 名称 + /// + public string Name { get; set; } + + /// + /// 父级权限Id + /// + public long ParentId { get; set; } + + /// + /// 状态(字典 0正常 1停用 2删除) + /// + public int Status { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehicleGroup/Services/IVehicleGroupService.cs b/src/Znyc.Dispatching.Application/VehicleGroup/Services/IVehicleGroupService.cs new file mode 100644 index 0000000..ffecc31 --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehicleGroup/Services/IVehicleGroupService.cs @@ -0,0 +1,15 @@ +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Application +{ + public interface IVehicleGroupService + { + /// + /// 新增车辆分组 + /// + /// + /// + Task InsertAsync(VehicleGroupAddInput input); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehicleGroup/Services/VehicleGroupService.cs b/src/Znyc.Dispatching.Application/VehicleGroup/Services/VehicleGroupService.cs new file mode 100644 index 0000000..fb8177d --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehicleGroup/Services/VehicleGroupService.cs @@ -0,0 +1,90 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Mapster; +using MapsterMapper; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Application +{ + /// + /// 车辆分组服务 + /// + [ApiDescriptionSettings(Name = "VehicleGroup", Order = 146, IgnoreApi = true)] + public class VehicleGroupService : IVehicleGroupService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IMapper _mapper; + private readonly IRepository _repository; + private readonly IUserManager _userManager; + + public VehicleGroupService( + IRepository repository, + IMapper mapper, + ICacheService cacheService, + IUserManager userManager + ) + { + _repository = repository; + _mapper = mapper; + _cacheService = cacheService; + _userManager = userManager; + } + + /// + /// 新增车辆分组 + /// + /// + /// + public async Task InsertAsync(VehicleGroupAddInput input) + { + VehicleGroup vehicleGroup = _mapper.Map(input); + Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry result = await _repository.InsertNowAsync(vehicleGroup); + if (result.IsNull()) + { + throw Oops.Oh(ErrorCode.D1011); + } + + return result.Entity; + } + + /// + /// 获取车辆分组 + /// + /// + [HttpGet] + public async Task> GetVehicleGroupListAsync() + { + List list = await _cacheService.GetVehicleGroupListAsync(_userManager.CompanyId); + if (list.IsNull()) + { + list = await SyncVehicleGroupListCache(); + } + + return list.Adapt>(); + ; + } + + /// + /// 同步车辆分组缓存 + /// + /// + [NonAction] + private async Task> SyncVehicleGroupListCache() + { + List list = await _repository.DetachedEntities + .Where(x => x.Status == CommonStatusEnum.ENABLE && x.CompanyId == _userManager.CompanyId) + .ToListAsync(); + await _cacheService.SetVehicleGroupListAsync(_userManager.CompanyId, list); + return list; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehiclePerson/Dto/Input/VehiclePersonAddInput.cs b/src/Znyc.Dispatching.Application/VehiclePerson/Dto/Input/VehiclePersonAddInput.cs new file mode 100644 index 0000000..df28407 --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehiclePerson/Dto/Input/VehiclePersonAddInput.cs @@ -0,0 +1,32 @@ +namespace Znyc.Dispatching.Application +{ + public class VehiclePersonAddInput + { + /// + /// 车辆 + /// + public long VehicleId { get; set; } + + /// + /// 车组人员Id + /// + public long UserId { get; set; } + + + /// + /// 员工名 + /// + public string UserName { get; set; } + + + /// + /// 手机号 + /// + public string UserPhone { get; set; } + + /// + /// 是否司机 + /// + public bool IsDriver { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehiclePerson/Dto/Input/VehiclePersonUpdateInput.cs b/src/Znyc.Dispatching.Application/VehiclePerson/Dto/Input/VehiclePersonUpdateInput.cs new file mode 100644 index 0000000..0b3b4dd --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehiclePerson/Dto/Input/VehiclePersonUpdateInput.cs @@ -0,0 +1,11 @@ +namespace Znyc.Dispatching.Application +{ + public class VehiclePersonUpdateInput : VehiclePersonAddInput + { + /// + /// + /// + public long Id { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehiclePerson/Dto/OutPut/VehiclePersonOutput.cs b/src/Znyc.Dispatching.Application/VehiclePerson/Dto/OutPut/VehiclePersonOutput.cs new file mode 100644 index 0000000..18dc39f --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehiclePerson/Dto/OutPut/VehiclePersonOutput.cs @@ -0,0 +1,42 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class VehiclePersonOutput + { + /// + /// Id + /// + public long Id { get; set; } + + /// + /// 车辆Id + /// + public long VehicleId { get; set; } + + /// + /// 员工Id + /// + public long UserId { get; set; } + + /// + /// 员工名称 + /// + public string UserName { get; set; } + + /// + /// 手机号 + /// + public string UserPhone { get; set; } + + /// + /// 是否司机 + /// + public bool IsDriver { get; set; } + + /// + /// + /// + public bool IsDeleted { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehiclePerson/Services/IVehiclePersonService.cs b/src/Znyc.Dispatching.Application/VehiclePerson/Services/IVehiclePersonService.cs new file mode 100644 index 0000000..0d8d556 --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehiclePerson/Services/IVehiclePersonService.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IVehiclePersonService + { + Task> GetByIdAsync(long id); + } +} diff --git a/src/Znyc.Dispatching.Application/VehiclePerson/Services/VehiclePersonService.cs b/src/Znyc.Dispatching.Application/VehiclePerson/Services/VehiclePersonService.cs new file mode 100644 index 0000000..d6b2558 --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehiclePerson/Services/VehiclePersonService.cs @@ -0,0 +1,38 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Application +{ + /// + ///车组人员信息联系人管理 + /// + [ApiDescriptionSettings(Name = "vehicleperson", Order = 145)] + public class VehiclePersonService : IVehiclePersonService, IDynamicApiController, ITransient + { + private readonly IRepository _repository; + private readonly ICacheService _cacheService; + + public VehiclePersonService(IRepository repository, + ICacheService cacheService) + { + _repository = repository; + _cacheService = cacheService; + } + + /// + /// 根据车辆Id查询车组人员信息 + /// + /// + [HttpGet] + [Route("api/v1/vehicle/persons/{vehicleId}")] + public async Task> GetByIdAsync(long vehicleId) + { + return await _cacheService.GetVehiclePersonAsync(vehicleId); + } + } +} diff --git a/src/Znyc.Dispatching.Application/VehicleType/Dto/Input/VehicleTypeInsertInput.cs b/src/Znyc.Dispatching.Application/VehicleType/Dto/Input/VehicleTypeInsertInput.cs new file mode 100644 index 0000000..fd1590b --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehicleType/Dto/Input/VehicleTypeInsertInput.cs @@ -0,0 +1,19 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// 新增车型 + /// + public class VehicleTypeInsertInput + { + /// + /// 名称 + /// + public string Name { get; set; } + + + /// + /// 状态(字典 0正常 1停用 2删除) + /// + public bool Status { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Application/VehicleType/Dto/Input/VehicleTypeUpdateInput.cs b/src/Znyc.Dispatching.Application/VehicleType/Dto/Input/VehicleTypeUpdateInput.cs new file mode 100644 index 0000000..5f6b20f --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehicleType/Dto/Input/VehicleTypeUpdateInput.cs @@ -0,0 +1,14 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + /// + public class VehicleTypeUpdateInput : VehicleTypeInsertInput + { + /// + /// + /// + public long Id { get; set; } + + } +} diff --git a/src/Znyc.Dispatching.Application/VehicleType/Dto/OutPut/VehicleTypeOutput.cs b/src/Znyc.Dispatching.Application/VehicleType/Dto/OutPut/VehicleTypeOutput.cs new file mode 100644 index 0000000..3393864 --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehicleType/Dto/OutPut/VehicleTypeOutput.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Application +{ + + public class VehicleTypeBaiscList + { + public long Total { get; set; } + + public List VehicleTypeLetterOutputs { get; set; } + } + + + public class VehicleTypeLetterOutput + { + + public string Char { get; set; } + + public List List { get; set; } + } + + public class VehicleTypeOutput + { + /// + /// + public long Id { get; set; } + + + /// + /// 匹配索引列表,与车组人员共用一个列表,所以需增加UserId来进行匹配 + /// + public long UserId + { + get + { + return Id; + } + set + { + Id = value; + } + } + /// + /// 名称 + /// + public string Name { get; set; } + + ///// + ///// 父级权限Id + ///// + //public long ParentId { get; set; } + + ///// + ///// 状态(字典 0正常 1停用 2删除) + ///// + public int Status { get; set; } + } + +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehicleType/Services/IVehicleTypeService.cs b/src/Znyc.Dispatching.Application/VehicleType/Services/IVehicleTypeService.cs new file mode 100644 index 0000000..b222aa2 --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehicleType/Services/IVehicleTypeService.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IVehicleTypeService + { + Task> ListAsync(string key, int status, int currentPage = 1, int pageSize = 10); + + public Task InsertAsync(VehicleTypeInsertInput vehicleTypeInsertInput); + + public Task UpdateAsync(VehicleTypeUpdateInput vehicleTypeUpdateInput); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/VehicleType/Services/VehicleTypeService.cs b/src/Znyc.Dispatching.Application/VehicleType/Services/VehicleTypeService.cs new file mode 100644 index 0000000..5510916 --- /dev/null +++ b/src/Znyc.Dispatching.Application/VehicleType/Services/VehicleTypeService.cs @@ -0,0 +1,113 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Mapster; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Helpers; + +namespace Znyc.Dispatching.Application +{ + /// + /// 车辆类型服务 + /// + [ApiDescriptionSettings(Name = "VehicleType", Order = 146)] + public class VehicleTypeService : IVehicleTypeService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _repository; + private readonly IUserManager _userManager; + private string[] INDEX_STRINGS = {"A", "B", "C", "D", "E", "F", "G", "H", "I", + "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", + "W", "X", "Y", "Z", "#"}; + + + + public VehicleTypeService( + IRepository repository, + ICacheService cacheService, + IUserManager userManager + ) + { + _repository = repository; + _cacheService = cacheService; + _userManager = userManager; + } + + + /// + /// + /// + /// + /// + [HttpPost] + [Route("api/v1/vehicletype")] + public async Task InsertAsync(VehicleTypeInsertInput vehicleTypeInsertInput) + { + var result = false; + if (vehicleTypeInsertInput.IsNotNull()) + { + var vehicleType = vehicleTypeInsertInput.Adapt(); + vehicleType.CompanyId = _userManager.CompanyId; + vehicleType.ParentId = 0; + long id = (await _repository.InsertNowAsync(vehicleType)).Entity.Id; + if (id > 0) + { + result = true; + } + } + return result; + } + + + /// + /// + /// + /// + [HttpGet] + [Route("api/v1/vehicletypes/search")] + public async Task> ListAsync(string key, int status, int currentPage = 1, int pageSize = 10) + { + var vehicleTypes = (await _repository.DetachedEntities.Where(x => x.CompanyId == _userManager.CompanyId) + .Where(key.IsNotEmptyOrNull(), x => x.Name.Contains(key)) + .Where(status > 0, x => x.Status) + .OrderBy(x => x.Name) + .ToPagedListAsync(currentPage, pageSize)).Adapt>(); + + return vehicleTypes; + } + + + /// + /// UpdateAsync + /// + /// + /// + [HttpPut] + [Route("api/v1/vehicletype")] + public async Task UpdateAsync(VehicleTypeUpdateInput vehicleTypeUpdateInput) + { + var result = false; + if (vehicleTypeUpdateInput.IsNotNull()) + { + var vehicleType = await _repository.FindAsync(vehicleTypeUpdateInput.Id); + if (vehicleType.IsNotNull()) + { + vehicleType.Name = vehicleTypeUpdateInput.Name; + vehicleType.Status = vehicleTypeUpdateInput.Status; + long id = (await _repository.UpdateNowAsync(vehicleType)).Entity.Id; + if (id > 0) + { + result = true; + } + } + } + return result; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/WxUserRelation/Services/IWxUserRelationService.cs b/src/Znyc.Dispatching.Application/WxUserRelation/Services/IWxUserRelationService.cs new file mode 100644 index 0000000..2c882cc --- /dev/null +++ b/src/Znyc.Dispatching.Application/WxUserRelation/Services/IWxUserRelationService.cs @@ -0,0 +1,15 @@ +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Application +{ + public interface IWxUserRelationService + { + /// + /// + /// + /// + /// + /// + Task AddOrUpdateAsync(long userId, string openId, string unionId); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/WxUserRelation/Services/WxUserRelationService.cs b/src/Znyc.Dispatching.Application/WxUserRelation/Services/WxUserRelationService.cs new file mode 100644 index 0000000..3d3bf63 --- /dev/null +++ b/src/Znyc.Dispatching.Application/WxUserRelation/Services/WxUserRelationService.cs @@ -0,0 +1,50 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Application +{ + /// + /// 车辆类型服务 + /// + [ApiDescriptionSettings(Name = "wxUserRelation", Order = 10, IgnoreApi = true)] + public class WxUserRelationService : IWxUserRelationService, IDynamicApiController, ITransient + { + private readonly IRepository _repository; + + public WxUserRelationService( + IRepository repository + ) + { + _repository = repository; + } + + [NonAction] + public async Task AddOrUpdateAsync(long userId, string openId, string unionId) + { + var wxUserRelation = + await _repository.Where(x => x.UnionId == unionId).FirstOrDefaultAsync(); + if (wxUserRelation.IsNull()) + { + await _repository.InsertNowAsync(new WxUserRelation + { + UnionId = unionId, + OpenId = openId, + UserId = userId, + WxOfficialOpenId = "" + }); + } + else + { + wxUserRelation.OpenId = openId; + wxUserRelation.UserId = userId; + await _repository.UpdateNowAsync(wxUserRelation); + } + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Yard/Dto/Input/YardAddInput.cs b/src/Znyc.Dispatching.Application/Yard/Dto/Input/YardAddInput.cs new file mode 100644 index 0000000..964a986 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Yard/Dto/Input/YardAddInput.cs @@ -0,0 +1,41 @@ +using System.ComponentModel.DataAnnotations; + +namespace Znyc.Dispatching.Application +{ + /// + /// 车场输入实体 + /// + public class YardAddInput + { + /// + /// 精度 + /// + [Required(ErrorMessage = "地址不能为空!")] + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + [Required(ErrorMessage = "地址不能为空!")] + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 联系人 + /// + [MaxLength(8, ErrorMessage = "联系人不得超过8个字")] + public string ContactPerson { get; set; } + + /// + /// 联系人电话 + /// + //[Required(ErrorMessage = "联系人电话不能为空!"), MaxLength(11, ErrorMessage = "联系电话不能超过11位")] + [RegularExpression("^[1][3,4,5,6,7,8,9][0-9]{9}$", ErrorMessage = "请输入正确的手机号码")] + [MaxLength(11, ErrorMessage = "联系电话不能超过11位")] + public string ContactPhone { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Yard/Dto/Input/YardUpdateInput.cs b/src/Znyc.Dispatching.Application/Yard/Dto/Input/YardUpdateInput.cs new file mode 100644 index 0000000..6fad033 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Yard/Dto/Input/YardUpdateInput.cs @@ -0,0 +1,9 @@ +namespace Znyc.Dispatching.Application +{ + /// + /// + public class YardUpdateInput : YardAddInput + { + public long Id { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Yard/Dto/OutPut/YardListOutput.cs b/src/Znyc.Dispatching.Application/Yard/Dto/OutPut/YardListOutput.cs new file mode 100644 index 0000000..4f56a48 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Yard/Dto/OutPut/YardListOutput.cs @@ -0,0 +1,28 @@ + +namespace Znyc.Dispatching.Application +{ + public class YardListOutput + { + public long Id { get; set; } + /// + /// 精度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 是否默认 + /// + public bool IsDefault { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Application/Yard/Dto/OutPut/YardOutput.cs b/src/Znyc.Dispatching.Application/Yard/Dto/OutPut/YardOutput.cs new file mode 100644 index 0000000..ac7daa1 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Yard/Dto/OutPut/YardOutput.cs @@ -0,0 +1,47 @@ +namespace Znyc.Dispatching.Application +{ + public class YardOutput + { + /// + /// 主键 + /// + public long Id { get; set; } + + /// + /// 精度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 联系人 + /// + public string ContactPerson { get; set; } + + /// + /// 联系人电话 + /// + public string ContactPhone { get; set; } + + /// + /// 是否默认 + /// + public bool IsDefault { get; set; } + + /// + /// 状态(字典 0正常 1停用 2删除) + /// + public int Status { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Yard/Services/IYardService.cs b/src/Znyc.Dispatching.Application/Yard/Services/IYardService.cs new file mode 100644 index 0000000..f9e2513 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Yard/Services/IYardService.cs @@ -0,0 +1,7 @@ +namespace Znyc.Dispatching.Application +{ + public interface IYardService + { + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Yard/Services/YardService.cs b/src/Znyc.Dispatching.Application/Yard/Services/YardService.cs new file mode 100644 index 0000000..421be04 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Yard/Services/YardService.cs @@ -0,0 +1,202 @@ +using Furion.DatabaseAccessor; +using Furion.DependencyInjection; +using Furion.DynamicApiController; +using Furion.FriendlyException; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Application +{ + /// + /// 车场服务 + /// + [ApiDescriptionSettings(Name = "yard", Order = 30)] + public class YardService : IYardService, IDynamicApiController, ITransient + { + private readonly ICacheService _cacheService; + private readonly IRepository _repository; + private readonly IUserManager _userManager; + private readonly IRepository _userYardRepository; + private readonly IUserService _userService; + + public YardService( + IRepository repository, + IUserManager userManager, + ICacheService cacheService, + IRepository userYardRepository, + IUserService userService + ) + { + _repository = repository; + _userManager = userManager; + _cacheService = cacheService; + _userYardRepository = userYardRepository; + _userService = userService; + } + + /// + /// 车场信息 + /// + /// + /// + /// + [HttpGet] + public async Task> PageAsync(int currentPage, int pageSize) + { + List yards = await _cacheService.GetYardListAsync(_userManager.CompanyId); + UserYard userYard = await _userYardRepository.DetachedEntities + .FirstOrDefaultAsync(x => x.UserId == _userManager.UserId && x.CompanyId == _userManager.CompanyId && x.IsDefault == true); + if (userYard.IsNotNull()) + { + foreach (var item in yards) + { + if (item.Id == userYard.YardId) + { + item.IsDefault = true; + } + } + } + PagedList data = new PagedList + { + Items = yards.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(), + TotalCount = yards.Count + }; + return data; + } + + /// + /// 根据id获取车场信息 + /// + /// + [HttpGet] + public async Task GetYardByIdAsync(long id) + { + return await _cacheService.GetYardAsync(id); + } + + /// + /// 添加车场信息 + /// + /// + /// + [HttpPost] + [UnitOfWork] + public async Task InsertAsync(YardAddInput input) + { + await _repository.InsertAsync(new Yard + { + CompanyId = _userManager.CompanyId, + ContactPerson = input.ContactPerson, + ContactPhone = input.ContactPhone, + Longitude = input.Longitude, + Latitude = input.Latitude, + Address = input.Address, + Status = (int)CommonStatusEnum.ENABLE + }); + //清除车场列表Cache + await _cacheService.RemoveYardListAsync(_userManager.CompanyId); + //清楚公司Cache + await _cacheService.RemoveCompanyAsync(_userManager.CompanyId); + } + + /// + /// 编辑车场信息 + /// + /// + [HttpPut] + [UnitOfWork] + public async Task UpdateAsync(YardUpdateInput input) + { + Yard yard = await _repository.FindOrDefaultAsync(input.Id); + yard.ContactPerson = input.ContactPerson; + yard.ContactPhone = input.ContactPhone; + yard.Latitude = input.Latitude; + yard.Longitude = input.Longitude; + yard.Address = input.Address; + Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry result = await _repository.UpdateNowAsync(yard); + if (result.IsNull()) + { + throw Oops.Oh("更新车场信息失败"); + } + + //清除车场Cache + await _cacheService.RemoveYardAsync(yard.Id); + //清除车场列表Cache + await _cacheService.RemoveYardListAsync(_userManager.CompanyId); + //清除公司Cache + await _cacheService.RemoveCompanyAsync(_userManager.CompanyId); + } + + /// + /// 删除车场信息 + /// + /// + /// + [HttpDelete] + public async Task RemoveYardByIdAsync(long id) + { + Yard yard = await _repository + .FirstOrDefaultAsync(x => x.Id == id && x.CompanyId == _userManager.CompanyId); + if (yard.IsNull()) + { + throw Oops.Oh("车场不存在"); + } + //删除与车场相关 + List userYards = await _userYardRepository.Where(x => x.YardId == id).ToListAsync(); + userYards.ForEach(x => { x.IsDeleted = true; }); + await _userYardRepository.UpdateNowAsync(userYards); + + yard.IsDeleted = true; + await _repository.UpdateIncludeNowAsync(yard, new[] { nameof(Yard.IsDeleted) }); + await _cacheService.RemoveYardAsync(id); + await _cacheService.RemoveYardListAsync(_userManager.CompanyId); + //清除公司Cache + await _cacheService.RemoveCompanyAsync(_userManager.CompanyId); + } + + /// + /// 修改默认车场信息 + /// + /// + [HttpPut] + [UnitOfWork] + public async Task UpdateIsDefaultAsync(long id) + { + UserYard oldUserYard = await _userYardRepository.FirstOrDefaultAsync(x => x.IsDefault == true + && x.CompanyId == _userManager.CompanyId && x.UserId == _userManager.UserId); + if (oldUserYard.IsNotNull()) + { + oldUserYard.IsDefault = false; + await _userYardRepository.UpdateNowAsync(oldUserYard); + } + UserYard newUserYard = await _userYardRepository.FirstOrDefaultAsync(x => x.YardId == id + && x.CompanyId == _userManager.CompanyId && x.UserId == _userManager.UserId); + if (newUserYard.IsNotNull()) + { + newUserYard.IsDefault = true; + await _userYardRepository.UpdateNowAsync(newUserYard); + } + else + { + await _userYardRepository.InsertAsync(new UserYard + { + UserId = _userManager.UserId, + YardId = id, + CompanyId = _userManager.CompanyId, + IsDefault = true + }); + } + + //清除公司Cache + await _cacheService.RemoveCompanyAsync(_userManager.CompanyId); + } + } + + +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Znyc.Dispatching.Application.csproj b/src/Znyc.Dispatching.Application/Znyc.Dispatching.Application.csproj new file mode 100644 index 0000000..fe90e2b --- /dev/null +++ b/src/Znyc.Dispatching.Application/Znyc.Dispatching.Application.csproj @@ -0,0 +1,59 @@ + + + net6.0 + 1701;1702;1591 + Znyc.Dispatching.Application.xml + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/Znyc.Dispatching.Application.xml b/src/Znyc.Dispatching.Application/Znyc.Dispatching.Application.xml new file mode 100644 index 0000000..c51ed68 --- /dev/null +++ b/src/Znyc.Dispatching.Application/Znyc.Dispatching.Application.xml @@ -0,0 +1,5205 @@ + + + + Znyc.Dispatching.Application + + + + + 系统缓存服务 + + + + + 获取短信验证码缓存 + + + + + + + 设置短信验证码缓存 + + + + + + + + 删除短信验证码缓存 + + + + + + + 获取权限缓存(按钮) + + + + + + + 缓存权限 + + + + + + + + 同步车辆分组缓存 + + + + + + + + 获取车辆分组缓存 + + + + + + + 同步车辆类型缓存 + + + + + + + 获取车辆分组缓存 + + + + + + 同步角色菜单缓存 + + + + + + + + 获取角色菜单缓存 + + + + + + 删除角色菜单缓存 + + + + + + + 同步角色缓存 + + + + + + + 获取角色缓存 + + + + + + 同步字典类型缓存 + + + + + + + 获取字典缓存 + + + + + + 同步公司缓存 + + + + + + + 获取公司缓存 + + + + + + + + 删除公司缓存 + + + + + + + 同步用户缓存 + + + + + + + 获取用户缓存 + + + + + + 移除用户缓存 + + + + + + + 删除用户所有缓存 + + + + + + 写入token + + + + + + + + 移除token + + + + + + + 获取token + + + + + + + 设置公司车辆缓存 + + + + + + + + 删除公司车辆缓存 + + + + + + + 删除公司车辆缓存 + + + + + + + 获取公司车辆缓存 + + + + + + + 获取公司车辆缓存 + + + + + + + 设置车辆缓存 + + + + + + + 删除车辆缓存 + + + + + + + 获取车辆缓存 + + + + + + + 设置员工缓存 + + + + + + + 删除员工缓存 + + + + + + + 获取员工缓存 + + + + + + + 设置员工列表缓存 + + + + + + + + 删除员工列表缓存 + + + + + + + 获取员工列表缓存 + + + + + + + 设置未读警报提醒缓存 + + + + + + + 删除未读警报提醒缓存 + + + + + + + 获取未读警报提醒缓存 + + + + + + 同步轨迹回放缓存 + + + + + + + + + + + 获取轨迹回放缓存 + + + + + + + + + 删除轨迹回放缓存 + + + + + + + + + 设置车场缓存 + + + + + + + 删除车场缓存 + + + + + + + 获取车场缓存 + + + + + + + 设置车场列表缓存 + + + + + + + + 删除车场列表缓存 + + + + + + + 获取车场列表缓存 + + + + + + + 同步工程列表缓存 + + + + + + + + 获取工程列表缓存 + + + + + + + 删除工程列表缓存 + + + + + + + 设置工程缓存 + + + + + + + 删除工程缓存 + + + + + + + 获取工程缓存 + + + + + + + 设置订单列表缓存 + + + + + + + + 删除订单列表缓存 + + + + + + + 获取订单列表缓存 + + + + + + + 设置车辆车组人员缓存 + + + + + + + + 删除车辆车组人员缓存 + + + + + + + 获取车辆车组人员缓存 + + + + + + + 设置缓存 + + + + + + + + 删除缓存 + + + + + + + 获取缓存 + + + + + + + 设置缓存 + + + + + + + 删除缓存 + + + + + + + 获取缓存 + + + + + + + 获取缓存 + + + + + + + 获取短信验证码 + + + + + + + 设置验证码缓存 + + + + + + + + 删除验证码 + + + + + + + 获取权限缓存(按钮) + + + + + + + 缓存权限 + + + + + + + + 同步车辆分组缓存 + + + + + + + + 获取车辆分组缓存 + + + + + + + 同步车辆类型缓存 + + + + + + + 获取车辆类型缓存 + + + + + + 同步角色菜单缓存 + + + + + + + + 获取角色菜单缓存 + + + + + + + 删除角色菜单缓存 + + + + + + + 同步角色缓存 + + + + + + + 获取角色缓存 + + + + + + 获取字典缓存 + + + + + + 同步字典缓存 + + + + + + + 同步公司缓存 + + + + + + + 获取公司缓存 + + + + + + + + 删除公司缓存 + + + + + + + 同步用户缓存 + + + + + + + 获取用户缓存 + + + + + + + 移除用户缓存 + + + + + + + 删除用户所有缓存 + + + + + + 写入token + + + + + + + + 移除token + + + + + + + 获取token + + + + + + + 发布 + + + + + + + + 订阅 + + + + + + + 设置公司车辆缓存 + + + + + + + + 删除公司车辆缓存 + + + + + + + 删除公司车辆缓存 + + + + + + + 获取所有公司车辆缓存 + + + + + + + 获取公司车辆缓存 + + + + + + + 设置车辆缓存 + + + + + + + 删除车辆缓存 + + + + + + + 获取车辆缓存 + + + + + + + 设置车辆缓存 + + + + + + + 删除员工缓存 + + + + + + + 获取员工缓存 + + + + + + + 设置员工列表缓存 + + + + + + + + 删除员工列表缓存 + + + + + + + 获取员工列表缓存 + + + + + + + 设置未读警报提醒缓存 + + + + + + + 删除未读警报提醒缓存 + + + + + + + 获取未读警报提醒缓存 + + + + + + 同步轨迹回放缓存 + + + + + + + + + + + 获取轨迹回放缓存 + + + + + + + + + 删除轨迹回放缓存 + + + + + + + + + 设置车场缓存 + + + + + + + 删除车场缓存 + + + + + + + 获取车场缓存 + + + + + + + 设置车场列表缓存 + + + + + + + + 删除车场列表缓存 + + + + + + + 获取车场列表缓存 + + + + + + + 同步工程列表缓存 + + + + + + + + 获取工程列表缓存 + + + + + + + 删除工程列表缓存 + + + + + + + 设置工程缓存 + + + + + + + 删除工程缓存 + + + + + + + 获取工程缓存 + + + + + + + 设置车辆车组人员缓存 + + + + + + + + 删除车辆车组人员缓存 + + + + + + + 获取车辆车组人员缓存 + + + + + + + 设置缓存 + + + + + + + + 删除缓存 + + + + + + + 获取缓存 + + + + + + + 设置缓存 + + + + + + + + 删除缓存 + + + + + + + 获取缓存 + + + + + + + 是否存在 + + + + + + + 公司输入实体 + + + + + 公司名称 + + + + + 联系人 + + + + + 联系人电话 + + + + + 精度 + + + + + 纬度 + + + + + 地址 + + + + + OpenId + + + + + + + + + 平台入驻 + + + + + JsCode + + + + + 用户名 + + + + + 头像 + + + + + 手机号 + + + + + 公司名称 + + + + + 精度 + + + + + 纬度 + + + + + 地址 + + + + + 主键 + + + + + 公司名称 + + + + + 公司Logo + + + + + 精度 + + + + + 纬度 + + + + + 地址 + + + + + 状态(字典 0正常 1停用 2删除) + + + + + 停留标示Id + + + + + 车场 + + + + + 一键派工是否显示工程名称 + + + + + 调度角色是否有添 加工程名称的权限 + + + + + 是否启用任务车型选项,默认为关 + + + + + 公司服务 + + + + + 获取当前公司信息 + + + + + + 根据Id获取公司信息 + + + + + + + 更新公司信息 + + + + + + + 平台入驻 + + + + + + + 获取位置名称 + + + + + + + + 修改公司停留标示 + + + + + + + 一键派工是否显示工程名称 + + + + + + 调度角色是否有添 加工程名称的权限 + + + + + + + + + + + + 注册公司 + + + + + + + 获取当前公司信息 + + + + + + 根据Id获取公司信息 + + + + + + 更新公司信息 + + + + + + + 获取位置名称 + + + + + + + + 修改公司停留标示 + + + + + + + 一键派工是否显示工程名称 + + + + + + 调度角色是否有添 加工程名称的权限 + + + + + + 新增是否启用任务车型选项,默认为关 + + + + + + Id + + + + + 匹配索引列表,与车组人员共用一个列表,所以需增加UserId来进行匹配 + + + + + 施工单位 + + + + + 联系人 + + + + + 联系电话 + + + + + 状态 + + + + + 施工单位 + + + + + InsertAsync + + + + + + + UpdateAsync + + + + + + + ListAsync + + + + + + InsertAsync + + + + + + + UpdateAsync + + + + + + + + + + + + + 字典服务 + + + + + 根据Id获取字典 + + + + + + + 根据code获取字典 + + + + + + + 根据Id获取字典 + + + + + + + 根据code获取字典 + + + + + + + 主键Id + + + + + 字典编码 + + + + + 字典值 + + + + + 字典名称 + + + + + 排序 + + + + + Cos服务 + + + + + 获取COS_Token + + + + + + 获取COS_Token + + + + + + 员工名 + + + + + 手机号 + + + + + 角色 + + + + + 角色名称 + + + + + 状态 + + + + + 员工头像 + + + + + + + + + 用户Id + + + + + + + + + + + + + + + 员工名 + + + + + 手机号 + + + + + + + + + 用户Id + + + + + 公司Id + + + + + 员工名 + + + + + 手机号 + + + + + 角色 + + + + + 角色名称 + + + + + 状态 + + + + + 员工头像 + + + + + 员工服务 + + + + + 员工信息 + + + + + 0全部,停用-1,正常1 + + + + + + + 根据id获取员工资料 + + + + + + 添加员工信息 + + + + + + + 编辑员工信息 + + + + + + 软删除员工信息 + + + + + + + 员工信息 + + + + + + + + + + + + 根据id获取员工资料 + + + + + + 添加员工信息 + + + + + + + 编辑员工信息 + + + + + + 软删除员工信息 + + + + + + + 审计日志服务 + + + + + 异常日志服务 + + + + + 登录实体 + + + + + getuserinfo信息 + + + + + 昵称 + + + + + 头像地址 + + + + + Token + + + + + 跳转路径 + + + + + 角色菜单列表 + + + + + 用户登录 + + + + + + + 登录服务 + + + + + 用户登录 + + + + + + + 清理缓存 + + + + + + 操作日志服务 + + + + + 菜单参数 + + + + + 父Id + + + + + 所属层级 + + + + + 名称 + + + + + 编码 + + + + + 菜单类型(字典 0目录 1菜单 2按钮) + + + + + 图标 + + + + + 路由地址 + + + + + 权限标识 + + + + + 是否外链 + + + + + 是否展开 + + + + + 是否显示 + + + + + 排序 + + + + + 详细描述 + + + + + CommonStatus + + + + + 菜单树(列表形式) + + + + + 菜单Id + + + + + 子集 + + + + + 系统菜单服务 + + + + + 获取用户权限(按钮权限标识集合) + + + + + + + 消息记录 + + + + + 接收者Id + + + + + 消息Id + + + + + 状态 + + + + + + + + + 主键 + + + + + 消息标题 + + + + + 消息内容 + + + + + 消息记录服务 + + + + + + + + + 消息标题 + + + + + 产品类型 + + + + + 消息内容 + + + + + + + + + 主键 + + + + + 消息类型 + + + + + 消息标题 + + + + + 消息内容 + + + + + 站内消息服务 + + + + + 分页查询系统消息通知 + + + + + + + + + 获取消息通知详情 + + + + + + + + + + + + 加油日期 + + + + + 车辆Id + + + + + 车俩编号 + + + + + 加油单号 + + + + + 加油量 + + + + + 油单价 + + + + + 金额 + + + + + + + + + 油耗统计 + + + + + 主键 + + + + + 车俩编号 + + + + + 加油量 + + + + + 金额 + + + + + 加油次数 + + + + + 加油总次数 + + + + + 加油总量 + + + + + 总金额 + + + + + 油耗统计 + + + + + 主键 + + + + + 加油日期 + + + + + 车俩编号 + + + + + 加油单号 + + + + + 加油量 + + + + + 油单价 + + + + + 金额 + + + + + 油耗服务 + + + + + 加油记录 + + + + + + + + + + 油耗统计 + + + + + + + + 根据Id获油耗信息 + + + + + + 添加油耗信息 + + + + + + + 修改油耗信息 + + + + + + + 删除油耗信息 + + + + + + + 油耗管理 + + + + + 加油记录 + + + + + + + + + + 油耗统计 + + + + + + + + 根据Id获油耗信息 + + + + + + 添加油耗信息 + + + + + + + 修改油耗信息 + + + + + + + 删除油耗信息 + + + + + + + + + + + 指派任务人员Id + + + + + 姓名 + + + + + 电话 + + + + + 是否司机 + + + + + + + + + OrderId + + + + + 订单内容 + + + + + 状态,,10=待指派,20=已指派,未接单,30=已接单,40=已出发,50=已完成(已签单),60=已离开,70=已评价 + + + + + 状态名称 + + + + + 车辆编号 + + + + + 车组人员 + + + + + 是否司机 + + + + + 创建时间 + + + + + + + + + UserId + + + + + 姓名 + + + + + 电话 + + + + + 是否司机 + + + + + + + + + 图片路径 + + + + + + + + + 图片路径 + + + + + 指派订单实体 + + + + + OrderId + + + + + 车辆Id + + + + + 车辆编号 + + + + + 是否外请车 + + + + + 车组人员 + + + + + 是否替换车组人员 + + + + + 车组人员 + + + + + 指派订单实体 + + + + + OrderId + + + + + 派单订单表实体 + + + + + 工程Id + + + + + 工程名称 + + + + + 业务员Id + + + + + 到场时间 + + + + + 经度 + + + + + 纬度 + + + + + 地址 + + + + + 订单内容 + + + + + 车辆Id + + + + + 是否外请车 + + + + + 车组人员 + + + + + 任务车型 + + + + + + + + + 签单 + + + + + OrderId + + + + + 图片路径 + + + + + 签单 + + + + + 待指派订单实体 + + + + + 工程Id + + + + + 工程名称 + + + + + 业务员Id + + + + + 到场时间 + + + + + 经度 + + + + + 纬度 + + + + + 地址 + + + + + 订单内容 + + + + + 任务车型 + + + + + 施工单位 + + + + + 施工单位 + + + + + 待指派订单实体 + + + + + OrderId + + + + + 订单列表返回 + + + + + 订单列表返回 + + + + + OrderId + + + + + 车辆Id,,冗余查询车辆列表状态 + + + + + 车辆编号 + + + + + 订单标题 + + + + + 订单内容 + + + + + 到场时间 + + + + + 订单来源 + + + + + 订单来源明细 + + + + + 是否外请车 + + + + + 状态, + + + + + 状态名称 + + + + + 经度 + + + + + 纬度 + + + + + 地址 + + + + + 工程Id + + + + + 工程名称 + + + + + 车组人员 + + + + + + + + + + 车组人员姓名 + + + + + 车组人员电话 + + + + + 指派人名称 + + + + + 指派人Id + + + + + 任务车型 + + + + + 任务车型名称 + + + + + 距离 + + + + + 预计到到时间 + + + + + + + + + + OrderId + + + + + 车辆Id + + + + + 车俩编号 + + + + + 工程Id + + + + + 工程名称 + + + + + 业务员Id + + + + + 到场时间 + + + + + 经度 + + + + + 纬度 + + + + + 地址 + + + + + 订单标题 + + + + + 订单内容 + + + + + 状态,,10=待指派,20=已指派,未接单,30=已接单,40=已出发,50=已完成(已签单),60=已离开,70=已评价 + + + + + 状态 + + + + + 订单来源,10=录入,20=报单 + + + + + 订单来源 + + + + + 车组人员 + + + + + 车组人员信息 + + + + + 签证明细 + + + + + 是否外请车 + + + + + + + + + + + + + + + 距离 + + + + + 预计到到时间 + + + + + 施工单位 + + + + + 施工单位 + + + + + 到家时间 + + + + + + + + + + + + + + + + + + + + 派单量 + + + + + 完成量 + + + + + 服务评价 + + + + + 派单量 + + + + + 完成量 + + + + + 服务评价 + + + + + 设备号 + + + + + 项目名称 + + + + + 员工姓名 + + + + + 派单量 + + + + + 接单量 + + + + + 完成量 + + + + + 服务评价 + + + + + 回单查询列表 + + 0全部,1未接单,2已结单,3已完成,4已评价 + + + + + + + + + + 任务统计--车辆 + + + + + + + + + + 任务统计--工程 + + + + + + + + + + 任务统计--人员 + + + + + + + + + + 派工订单管理 + + + + + 管理端任务列表 + + + + + + + + + + 保存待指派 + + + + + + + 指派订单 + + + + + + + 完成订单 + + + + + + + 删除订单 + + + + + + + 撤销订单 + + + + + + + 接单 + + + + + + + 签单 + + + + + + + 车组人员端任务列表 + + + + + + + + 外租伙伴端任务列表 + + + + + + + + 查询订单明细 + + + + + + + v1.2.2 工地联系人调整为非必填项,如果用户先录入 了工程名称基础数据,而且工程名称派工开关 设置为打开,而且用户派工时选择了工程名称 的情况下,则用户录入派工任务保存或指派成 功后,自动将任务内容里该工地联系人关联至 该工程的工地联系人这里 + + + + + + + + + 更新签证单 + + + + + + + 回单查询列表 + + 0全部,1未接单,2已结单,3已完成,4已评价 + + + + + + + + + + 任务统计--车辆 + + + + + + + + + + 任务统计--工程 + + + + + + + + + + 任务统计--人员 + + + + + + + + + + 任务统计--施工单位 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + . + + + + + + 公司输入实体 + + + + + 联系人Id,链接员工表Id + + + + + 联系人姓名 + + + + + 联系人电话 + + + + + + + + + 联系人Id,链接员工表Id + + + + + 联系人姓名 + + + + + 联系人电话 + + + + + 工程信息联系人管理 + + + + + 根据工程Id查询工程联系人 + + + + + + 工程输入实体 + + + + + 工程名称 + + + + + 业务员Id + + + + + 经度 + + + + + 纬度 + + + + + 地址 + + + + + 工地联系人Id + + + + + 是否启用 + + + + + 施工单位 + + + + + 施工单位 + + + + + + + + + Id + + + + + 工程名称 + + + + + 工程地址 + + + + + 经度 + + + + + 纬度 + + + + + 工地联系人(报单人) + + + + + 是否启用 + + + + + 业务员Id + + + + + 施工单位 + + + + + Id + + + + + 工程名称 + + + + + 业务员Id + + + + + 业务员 + + + + + 经度 + + + + + 纬度 + + + + + 地址 + + + + + 工地联系人(报单人) + + + + + 是否启用 + + + + + 施工单位 + + + + + 施工单位 + + + + + 工程服务 + + + + + 查询单个工程信息 + + + + + + 工程列表 + + + + + + + + + + 新增工程信息 + + + + + + + 更新公司信息 + + + + + + + 停用工程信息 + + + + + + + 工程管理 + + + + + 查询单个工程信息 + + + + + + 工程列表 + + -1全部,停用0,正常1 + + + + + + + + 新增工程信息 + + + + + + + 更新工程信息 + + + + + + + 停用工程信息 + + + + + + + 反馈明细 + + + + + 意见反馈服务 + + + + + 添加意见反馈 + + + + + + + 获取角色的菜单Id集合 + + + + + + + 获取角色菜单 + + + + + + 同步角色菜单 + + + + + + 角色菜单服务 + + + + + 获取角色的菜单Id集合 + + + + + + + 获取角色的菜单 + + + + + + 同步角色菜单 + + + + + + RoleOutput + + + + + Id + + + + + 名称 + + + + + 权限备注 + + + + + 角色服务 + + + + + 获取角色 + + + + + + 用户角色服务 + + + + + 获取用户的角色Id集合 + + + + + + + + + + + + + + + + + + jscode + + + + + EncryptedData + + + + + Iv + + + + + 用户输入实体 + + + + + 用户名 + + + + + 头像 + + + + + + + + + + 公司Id + + + + + 角色Id + + + + + 用户修改密码 + + + + + 手机号 + + + + + 旧密码 + + + + + 新密码 + + + + + 确认密码 + + + + + 验证码 + + + + + 用户输入实体 + + + + + 用户名 + + + + + 头像 + + + + + 电话 + + + + + 用户输出实体 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 电话 + + + + + 邀请用户注册并登陆 + + + + + + + 修改用户信息 + + + + + + + 用户服务 + + + + + 个人资料 + + + + + + 邀请用户注册并登陆 + + + + + + + 修改用户信息 + + + + + + + 更新用户信息 + + + + + + + + 解密电话号码 + + + + + + + 公司Id + + + + + 名称 + + + + + 父级权限Id + + + + + + + + + Id + + + + + 公司Id + + + + + 名称 + + + + + 父级权限Id + + + + + 状态(字典 0正常 1停用 2删除) + + + + + 新增车辆分组 + + + + + + + 车辆分组服务 + + + + + 新增车辆分组 + + + + + + + 获取车辆分组 + + + + + + 同步车辆分组缓存 + + + + + + 车辆 + + + + + 车组人员Id + + + + + 员工名 + + + + + 手机号 + + + + + 是否司机 + + + + + + + + + + + + + + Id + + + + + 车辆Id + + + + + 员工Id + + + + + 员工名称 + + + + + 手机号 + + + + + 是否司机 + + + + + + + + + + 车组人员信息联系人管理 + + + + + 根据车辆Id查询车组人员信息 + + + + + + 新增车型 + + + + + 名称 + + + + + 状态(字典 0正常 1停用 2删除) + + + + + + + + + + + + + + + + + + + 匹配索引列表,与车组人员共用一个列表,所以需增加UserId来进行匹配 + + + + + 名称 + + + + + 车辆类型服务 + + + + + + + + + + + + + + + + + + UpdateAsync + + + + + + + 基础信息-车辆编辑 + + + + + 车辆编号 + + + + + 车牌号 + + + + + 状态 + + + + + 车组人员 + + + + + 轨迹纠偏入参 + + + + + 维度 + + + + + 精度 + + + + + 角度 + + + + + 速度 + + + + + 时间 + + + + + 所属公司 + + + + + 车辆编号 + + + + + 车牌号 + + + + + 车辆类型 + + + + + 所属车组 + + + + + SIM卡号 + + + + + 设备类型 + + + + + 设备号 + + + + + 联系人 + + + + + 司机电话 + + + + + 状态(字典 0正常 1停用 2删除) + + + + + 打火状态 + + + + + 工作状态 + + + + + IEML号 + + + + + GPS时间 + + + + + 开通时间 + + + + + 到期时间 + + + + + 车辆编号 + + + + + 车牌号 + + + + + 联系人 + + + + + 联系人电话 + + + + + 超速最新未读时间 + + + + + 超速未读数 + + + + + 自编号 + + + + + 车牌号 + + + + + 地图 + + + + + 车辆编号 + + + + + 精度 + + + + + 图标 + + + + + + + + + + + + + + + + + + + + + + + + + 总数 + + + + + 超速记录输出集合 + + + + + 超速记录输出实体 + + + + + 所属车辆 + + + + + 所属公司 + + + + + 车辆编号 + + + + + GPS时间 + + + + + 车牌号 + + + + + 经度 + + + + + 纬度 + + + + + 方向 + + + + + 速度 + + + + + 地点 + + + + + 轨迹纠偏出参 + + + + + 数据体 + + + + + 30001错误表示抓路失败。当传入点数较少或较稀疏时,可能会导致抓路失败。 + + + + + + + + + + + + + + + 数据体 + + + + + 总距离 + + + + + 返回坐标合集 + + + + + 返回坐标合集 + + + + + 维度 + + + + + 经度 + + + + + 车辆编号 + + + + + 车牌号 + + + + + 总公里 + + + + + 总停留时间 + + + + + 轨迹点输出实体 + + + + + 停留点输出实体 + + + + + 经度 + + + + + 纬度 + + + + + GPS时间 + + + + + 速度 + + + + + 地址 + + + + + 方向 + + + + + 开始时间 + + + + + 结束时间 + + + + + 静止时长 + + + + + 是否是停留点 + + + + + 停留次数 + + + + + 打火状态 + + + + + ACC持续时长 + + + + + 工作状态 + + + + + 工作持续时长 + + + + + 总里程 + + + + + 经度 + + + + + 纬度 + + + + + 地址 + + + + + 开始时间 + + + + + 结束时间 + + + + + GPS时间 + + + + + 状态 + + + + + 停留点描述 + + + + + 停留时长描述 + + + + + 总里程 + + + + + 车辆编号 + + + + + 车牌号 + + + + + 状态 + + + + + 车组人员 + + + + + 车组人员姓名 + + + + + 车组人员电话 + + + + + 所属公司 + + + + + 车辆编号 + + + + + 车牌号 + + + + + 联系人 + + + + + 联系电话 + + + + + 状态(字典 1正常 -1停用 -2删除 0审核中) + + + + + 打火状态 + + + + + 工作状态 + + + + + Gps状态 + + + + + Gps状态名称 + + + + + GPS时间 + + + + + 最后通讯时间 + + + + + 速度 + + + + + 地址 + + + + + ACC持续时长 + + + + + 经度 + + + + + 纬度 + + + + + IMEI号 + + + + + 设备类型 + + + + + 开通时间 + + + + + 到期时间 + + + + + 设备类型 + + + + + 离线时长 + + + + + work工作时长 + + + + + 静止时长 + + + + + 是否开启超速报警 + + + + + 超速速度 + + + + + 是否激活 + + + + + 是否开启GPS + + + + + Sim卡号 + + + + + 更新时间 + + + + + Gps信号模式 1 GPS,2 基站 + + + + + 车辆任务状态 + + + + + 车组人员 + + + + + 位置基本信息报警标志位 --欠压 + + + + + Gps信号源 + + + + + 掉电 + + + + + 排序 + + + + + 方向 + + + + + 全部数 + + + + + 离线数 + + + + + 静止数 + + + + + 行驶数 + + + + + 根据id获取车辆Gps信息 + + + + + + + 获取地图信息 + + + + + + 更新车辆信息 + + + + + + + 轨迹回放纠偏 + + + + + + + + + 修改超速报警/速度 + + + + + + + + + 超速记录 + + + + + + + + 未读报警消息数 + + + + + + 同步轨迹 + + + + + + 基础数据-车辆管理列表 + + + + + + + + + + 基础数据-车辆信息 + + + + + + + 更新车辆基础信息 + + + + + + + 分页查询 + + + 0全部,1任务中,2空闲,3停用 + + + + + + + 车辆信息服务 + + + + + 根据id获取车辆Gps信息 + + + + + + + 获取地图信息 + + + + + + 分页查询 + + + 0全部,1任务中,2空闲,3停用 + + + + + + + 修改车辆信息 + + + + + + + 轨迹回放纠偏 + + + + + + + + + 修改超速报警/速度 + + + + + + + + + 超速报警列表 + + + + + + + + 未读报警消息数 + + + + + + 获取车辆GPS信息 + + 车辆Id + 开始时间 + 结束时间 + + + + + 轨迹点预处理(车辆) + + + + + + + 离线车辆报警 + + + + + + 同步轨迹 + + + + + + 轨迹回放纠偏 + + + + + + + + + + + 基础数据-车辆管理列表 + + + + + 0全部,停用-1,正常1 + + + + + 基础数据-车辆信息 + + + + + + + 更新车辆基础信息 + + + + + + + + + + + + + + + 车辆类型服务 + + + + + 车场输入实体 + + + + + 精度 + + + + + 纬度 + + + + + 地址 + + + + + 联系人 + + + + + 联系人电话 + + + + + + + + + 精度 + + + + + 纬度 + + + + + 地址 + + + + + 是否默认 + + + + + 主键 + + + + + 精度 + + + + + 纬度 + + + + + 地址 + + + + + 联系人 + + + + + 联系人电话 + + + + + 是否默认 + + + + + 状态(字典 0正常 1停用 2删除) + + + + + 车场服务 + + + + + 车场信息 + + + + + + + + 根据id获取车场信息 + + + + + + 添加车场信息 + + + + + + + 编辑车场信息 + + + + + + 删除车场信息 + + + + + + + 修改默认车场信息 + + + + + + 添加 + + + + + 施工单位 + + + + + 联系人 + + + + + 联系电话 + + + + + 状态 + + + + + 修改 + + + + + 主键Id + + + + + 添加 + + + + + 字典父级 + + + + + 字典名称 + + + + + 字典编码 + + + + + 字典值 + + + + + 描述 + + + + + 启用 + + + + + 修改 + + + + + 主键Id + + + + + 版本 + + + + + 任务调度参数 + + + + + 任务名称 + + + + + 执行间隔时间(单位秒) + + 5 + + + + Cron表达式 + + + + + 定时器类型 + + + + + 执行次数 + + + + + 请求url + + + + + 请求参数(Post,Put请求用) + + + + + Headers(可以包含如:Authorization授权认证) + 格式:{"Authorization":"userpassword.."} + + + + + 请求类型 + + + + + 备注 + + + + + 任务Id + + + + + 任务信息---任务详情 + + + + + Id + + + + + 任务名称 + + + + + 执行间隔时间(单位秒) + + + + + Cron表达式 + + + + + 定时器类型 + + + + + 执行次数 + + + + + 请求url + + + + + 请求参数(Post,Put请求用) + + + + + Headers(可以包含如:Authorization授权认证) + 格式:{"Authorization":"userpassword.."} + + + + + 请求类型 + + 2 + + + + 备注 + + + + + 定时器状态 + + + + + 异常信息 + + + + + 任务调度服务 + + + + diff --git a/src/Znyc.Dispatching.Application/applicationconfig.Development.json b/src/Znyc.Dispatching.Application/applicationconfig.Development.json new file mode 100644 index 0000000..beacb07 --- /dev/null +++ b/src/Znyc.Dispatching.Application/applicationconfig.Development.json @@ -0,0 +1,15 @@ +//v1.1.8业务要求设置为永不过期 +{ + "JWTSettings": { + "ValidateIssuerSigningKey": true, // 是否验证密钥,bool 类型,默认true + "IssuerSigningKey": + "3c1cbc3f546eda35168c3aa3cb91780fbe703f0996c6d123ea96dc85c70bbc0a", // 密钥,string 类型,必须是复杂密钥,长度大于16 + "ValidateIssuer": true, // 是否验证签发方,bool 类型,默认true + "ValidIssuer": "znyc", // 签发方,string 类型 + "ValidateAudience": true, // 是否验证签收方,bool 类型,默认true + "ValidAudience": "znyc", // 签收方,string 类型 + "ValidateLifetime": true, // 是否验证过期时间,bool 类型,默认true,建议true + "ExpiredTime": 864000, // 过期时间,long 类型,单位分钟 + "ClockSkew": 5 // 过期时间容错值,long 类型,单位秒,默认5秒 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/applicationconfig.Production.json b/src/Znyc.Dispatching.Application/applicationconfig.Production.json new file mode 100644 index 0000000..e1a9c69 --- /dev/null +++ b/src/Znyc.Dispatching.Application/applicationconfig.Production.json @@ -0,0 +1,15 @@ +//v1.1.8业务要求设置为永不过期 +{ + "JWTSettings": { + "ValidateIssuerSigningKey": true, // 是否验证密钥,bool 类型,默认true + "IssuerSigningKey": + "3c1cbc3f546eda35168c3aa3cb91780fbe703f0996c6d123ea96dc85c70bbc0a", // 密钥,string 类型,必须是复杂密钥,长度大于16 + "ValidateIssuer": true, // 是否验证签发方,bool 类型,默认true + "ValidIssuer": "znyc", // 签发方,string 类型 + "ValidateAudience": true, // 是否验证签收方,bool 类型,默认true + "ValidAudience": "znyc", // 签收方,string 类型 + "ValidateLifetime": true, // 是否验证过期时间,bool 类型,默认true,建议true + "ExpiredTime": 864000, // 过期时间,long 类型,单位分钟,默认20分钟 + "ClockSkew": 5 // 过期时间容错值,long 类型,单位秒,默认5秒 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Application/applicationconfig.Staging.json b/src/Znyc.Dispatching.Application/applicationconfig.Staging.json new file mode 100644 index 0000000..beacb07 --- /dev/null +++ b/src/Znyc.Dispatching.Application/applicationconfig.Staging.json @@ -0,0 +1,15 @@ +//v1.1.8业务要求设置为永不过期 +{ + "JWTSettings": { + "ValidateIssuerSigningKey": true, // 是否验证密钥,bool 类型,默认true + "IssuerSigningKey": + "3c1cbc3f546eda35168c3aa3cb91780fbe703f0996c6d123ea96dc85c70bbc0a", // 密钥,string 类型,必须是复杂密钥,长度大于16 + "ValidateIssuer": true, // 是否验证签发方,bool 类型,默认true + "ValidIssuer": "znyc", // 签发方,string 类型 + "ValidateAudience": true, // 是否验证签收方,bool 类型,默认true + "ValidAudience": "znyc", // 签收方,string 类型 + "ValidateLifetime": true, // 是否验证过期时间,bool 类型,默认true,建议true + "ExpiredTime": 864000, // 过期时间,long 类型,单位分钟 + "ClockSkew": 5 // 过期时间容错值,long 类型,单位秒,默认5秒 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Common/Extensions/GenericTypeExtensions.cs b/src/Znyc.Dispatching.Common/Extensions/GenericTypeExtensions.cs new file mode 100644 index 0000000..49b736b --- /dev/null +++ b/src/Znyc.Dispatching.Common/Extensions/GenericTypeExtensions.cs @@ -0,0 +1,30 @@ +using System; +using System.Linq; + +namespace Znyc.Dispatching.Common.Extensions +{ + public static class GenericTypeExtensions + { + public static string GetGenericTypeName(this Type type) + { + string? typeName = string.Empty; + + if (type.IsGenericType) + { + string? genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray()); + typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>"; + } + else + { + typeName = type.Name; + } + + return typeName; + } + + public static string GetGenericTypeName(this object @object) + { + return @object.GetType().GetGenericTypeName(); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Common/Extensions/LinqExtensions.cs b/src/Znyc.Dispatching.Common/Extensions/LinqExtensions.cs new file mode 100644 index 0000000..05767ce --- /dev/null +++ b/src/Znyc.Dispatching.Common/Extensions/LinqExtensions.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; + +namespace Znyc.Dispatching.Common.Extensions +{ + public static class LinqExtensions + { + public static IQueryable WhereIf(this IQueryable query, bool condition, + Expression> predicate) + { + return condition ? query.Where(predicate) : query; + } + + public static IQueryable WhereIf(this IQueryable query, bool condition, + Expression> predicate) + { + return condition ? query.Where(predicate) : query; + } + + public static IEnumerable WhereIf(this IEnumerable query, bool condition, Func predicate) + { + return condition ? query.Where(predicate) : query; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Common/Znyc.Dispatching.Common.csproj b/src/Znyc.Dispatching.Common/Znyc.Dispatching.Common.csproj new file mode 100644 index 0000000..3d282fb --- /dev/null +++ b/src/Znyc.Dispatching.Common/Znyc.Dispatching.Common.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + + + + + + + + + + + + diff --git a/src/Znyc.Dispatching.Core/Cache/CacheOptions.cs b/src/Znyc.Dispatching.Core/Cache/CacheOptions.cs new file mode 100644 index 0000000..7da0dcc --- /dev/null +++ b/src/Znyc.Dispatching.Core/Cache/CacheOptions.cs @@ -0,0 +1,15 @@ +using Furion.ConfigurableOptions; + +namespace Znyc.Dispatching.Core.Cache +{ + /// + /// 缓存配置 + /// + public class CacheOptions : IConfigurableOptions + { + /// + /// Redis配置 + /// + public string RedisConnectionString { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Cache/IRedisCache.cs b/src/Znyc.Dispatching.Core/Cache/IRedisCache.cs new file mode 100644 index 0000000..00b44af --- /dev/null +++ b/src/Znyc.Dispatching.Core/Cache/IRedisCache.cs @@ -0,0 +1,154 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using static CSRedis.CSRedisClient; + +namespace Znyc.Dispatching.Core.Cache +{ + /// + /// 缓存接口 + /// + public interface IRedisCache + { + /// + /// 用于在 key 存在时删除 key + /// + /// 键 + long Del(params string[] key); + + /// + /// 用于在 key 存在时删除 key + /// + /// 键 + /// + Task DelAsync(params string[] key); + + /// + /// 用于在 key 模板存在时删除 + /// + /// key模板 + /// + Task DelByPatternAsync(string pattern); + + /// + /// 检查给定 key 是否存在 + /// + /// 键 + /// + bool Exists(string key); + + /// + /// 检查给定 key 是否存在 + /// + /// 键 + /// + Task ExistsAsync(string key); + + /// + /// 获取指定 key 的值 + /// + /// 键 + /// + string Get(string key); + + /// + /// 获取指定 key 的值 + /// + /// byte[] 或其他类型 + /// 键 + /// + T Get(string key); + + /// + /// 获取指定 key 的值 + /// + /// 键 + /// + Task GetAsync(string key); + + /// + /// 获取指定 key 的值 + /// + /// byte[] 或其他类型 + /// 键 + /// + Task GetAsync(string key); + + /// + /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 + /// + /// 键 + /// 值 + bool Set(string key, object value); + + /// + /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 + /// + /// 键 + /// 值 + /// 有效期 + bool Set(string key, object value, TimeSpan expire); + + /// + /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 + /// + /// 键 + /// 值 + /// + Task SetAsync(string key, object value); + + /// + /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 + /// + /// 键 + /// 值 + /// 有效期 + /// + Task SetAsync(string key, object value, TimeSpan expire); + + /// + /// 获取所有缓存 + /// + /// + List GetAllKeys(); + + + /// + /// 缓存壳 + /// + /// + /// + /// + /// + /// + T CacheShell(string key, int timeoutSeconds, Func getDataAsync); + + + /// + /// 缓存壳 + /// + /// + /// + /// + /// + /// + Task CacheShellAsync(string key, int timeoutSeconds, Func> getDataAsync); + + + /// + /// 发布 + /// + /// + /// + /// + Task PublishAsync(string channel, string message); + + + /// + /// 订阅 + /// + /// + /// + SubscribeObject Subscribe(params (string, Action)[] channels); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Cache/RedisCache.cs b/src/Znyc.Dispatching.Core/Cache/RedisCache.cs new file mode 100644 index 0000000..f482836 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Cache/RedisCache.cs @@ -0,0 +1,167 @@ +using CSRedis; +using Furion.DependencyInjection; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using static CSRedis.CSRedisClient; + +namespace Znyc.Dispatching.Core.Cache +{ + /// + /// Redis缓存 + /// + public class RedisCache : IRedisCache, ISingleton + { + public RedisCache(IOptions cacheOptions) + { + CSRedisClient csredis = new CSRedisClient(cacheOptions.Value.RedisConnectionString); + RedisHelper.Initialization(csredis); + } + + public long Del(params string[] key) + { + return RedisHelper.Del(key); + } + + public Task DelAsync(params string[] key) + { + return RedisHelper.DelAsync(key); + } + + public async Task DelByPatternAsync(string pattern) + { + if (string.IsNullOrEmpty(pattern)) + { + return default; + } + + //pattern = Regex.Replace(pattern, @"\{.*\}", "*"); + string[] keys = await RedisHelper.KeysAsync(pattern); + if (keys != null && keys.Length > 0) + { + return await RedisHelper.DelAsync(keys); + } + + return default; + } + + public bool Exists(string key) + { + return RedisHelper.Exists(key); + } + + public Task ExistsAsync(string key) + { + return RedisHelper.ExistsAsync(key); + } + + public string Get(string key) + { + return RedisHelper.Get(key); + } + + public T Get(string key) + { + return RedisHelper.Get(key); + } + + public Task GetAsync(string key) + { + return RedisHelper.GetAsync(key); + } + + public Task GetAsync(string key) + { + return RedisHelper.GetAsync(key); + } + + public bool Set(string key, object value) + { + return RedisHelper.Set(key, value); + } + + public bool Set(string key, object value, TimeSpan expire) + { + return RedisHelper.Set(key, value, expire); + } + + public Task SetAsync(string key, object value) + { + return RedisHelper.SetAsync(key, value); + } + + public Task SetAsync(string key, object value, TimeSpan expire) + { + return RedisHelper.SetAsync(key, value, expire); + } + + public List GetAllKeys() + { + return RedisHelper.Keys("").ToList(); + } + + + /// + /// 缓存壳 + /// + /// + /// + /// + /// + /// + public T CacheShell(string key, int timeoutSeconds, Func getDataAsync) + { + return RedisHelper.CacheShell(key, timeoutSeconds, getDataAsync); + } + + /// + /// 缓存壳 + /// + /// + /// + /// + /// + /// + public Task CacheShellAsync(string key, int timeoutSeconds, Func> getDataAsync) + { + return RedisHelper.CacheShellAsync(key, timeoutSeconds, getDataAsync); + } + + + /// + /// 发布 + /// + /// + /// + /// + public async Task PublishAsync(string channel, string message) + { + return await RedisHelper.PublishAsync(channel, message); + } + + /// + /// 订阅 + /// + /// + /// + public SubscribeObject Subscribe(params (string, Action)[] channels) + { + return RedisHelper.Subscribe(channels); + } + + + /// + /// 发布 + /// + /// + /// + /// + public long Publish(string channel, string message) + { + return RedisHelper.Publish(channel, message); + } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Config/SmsProviderOptions.cs b/src/Znyc.Dispatching.Core/Config/SmsProviderOptions.cs new file mode 100644 index 0000000..4bb70da --- /dev/null +++ b/src/Znyc.Dispatching.Core/Config/SmsProviderOptions.cs @@ -0,0 +1,33 @@ +using Furion.ConfigurableOptions; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Core +{ + /// + /// 发送短信配置 + /// + [OptionsSettings("SMSProvider")] + public class SmsProviderOptions : IConfigurableOptions + { + public string SecretId { get; set; } + + public string SecretKey { get; set; } + + public string SmsSdkAppid { get; set; } + + public string Sign { get; set; } + + public string Region { get; set; } + + public List TemplateList { get; set; } + } + + public class TemplateList + { + public string ChangePassWordTemplateId { get; set; } + + public string RegisterTemplateId { get; set; } + + public string AddEmployeeTemplateId { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Config/UploadInfoOptions.cs b/src/Znyc.Dispatching.Core/Config/UploadInfoOptions.cs new file mode 100644 index 0000000..dde6b90 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Config/UploadInfoOptions.cs @@ -0,0 +1,21 @@ +using Furion.ConfigurableOptions; + +namespace Znyc.Dispatching.Core +{ + public class UploadInfoOptions : IConfigurableOptions + { + public string secretId { get; set; } + + public string secretKey { get; set; } + + public string bucket { get; set; } + + public string region { get; set; } + + public string allowPrefix { get; set; } + + public int durationSeconds { get; set; } + + public string[] allowActions { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Config/UploadOptions.cs b/src/Znyc.Dispatching.Core/Config/UploadOptions.cs new file mode 100644 index 0000000..34779ef --- /dev/null +++ b/src/Znyc.Dispatching.Core/Config/UploadOptions.cs @@ -0,0 +1,94 @@ +using Furion.ConfigurableOptions; +using System; +using System.IO; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Core +{ + /// + /// 上传配置 + /// + // [OptionsSettings("AppSettings:Upload")] + public class UploadOptions : IConfigurableOptions + { + public string SecretId { get; set; } + public string SecretKey { get; set; } + public string Bucket { get; set; } + public string Region { get; set; } + + /// + /// 头像上传配置 + /// + public FileUploadConfig Avatar { get; set; } + + /// + /// 文档图片上传配置 + /// + public FileUploadConfig Document { get; set; } + } + + /// + /// 文件上传配置 + /// + public class FileUploadConfig + { + private string _uploadPath; + + /// + /// 上传路径 + /// + public string UploadPath + { + get + { + if (_uploadPath.IsNull()) + { + _uploadPath = Path.Combine(AppContext.BaseDirectory, "upload").ToPath(); + } + + if (!Path.IsPathRooted(_uploadPath)) + { + _uploadPath = Path.Combine(AppContext.BaseDirectory, _uploadPath).ToPath(); + } + + return _uploadPath; + } + set => _uploadPath = value; + } + + /// + /// 请求路径 + /// + public string RequestPath { get; set; } + + /// + /// 读取路径 + /// + public string ReadPath { get; set; } + + /// + /// 路径格式 + /// + public string Format { get; set; } + + /// + /// 路径日期格式 + /// + public string DateTimeFormat { get; set; } + + /// + /// 文件大小 10M = 10 * 1024 * 1024 + /// + public int MaxSize { get; set; } + + /// + /// 最大允许上传个数 -1不限制 + /// + public int Limit { get; set; } = -1; + + /// + /// 文件格式 + /// + public string[] ContentType { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Config/WeixinSettingOptions.cs b/src/Znyc.Dispatching.Core/Config/WeixinSettingOptions.cs new file mode 100644 index 0000000..6faf6bf --- /dev/null +++ b/src/Znyc.Dispatching.Core/Config/WeixinSettingOptions.cs @@ -0,0 +1,51 @@ +using Furion.ConfigurableOptions; + +namespace Znyc.Dispatching.Core +{ + /// + /// 微信配置 + /// + [OptionsSettings("SenparcWeixinSetting")] + public class WeixinSettingOptions : IConfigurableOptions + { + /// + /// 是否调试模式 + /// + public bool IsDebug { get; set; } + + /// + /// 小程序 + /// + public string WxOpenAppId { get; set; } + + /// + /// + public string WxOpenAppSecret { get; set; } + + /// + /// + public string WxOpenToken { get; set; } + + /// + /// + public string WxOpenEncodingAESKey { get; set; } + + /// + /// + public string Token { get; set; } + + /// + /// + public string EncodingAESKey { get; set; } + + /// + /// 公众号 + /// + public string WeixinAppId { get; set; } + + /// + /// 公众号 + /// + public string WeixinAppSecret { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Const/ApiGroupConsts.cs b/src/Znyc.Dispatching.Core/Const/ApiGroupConsts.cs new file mode 100644 index 0000000..e8ab5df --- /dev/null +++ b/src/Znyc.Dispatching.Core/Const/ApiGroupConsts.cs @@ -0,0 +1,22 @@ +namespace Znyc.Dispatching.Core +{ + /// + /// + public class ApiGroupConsts + { + /// + /// 用户 + /// + public const string USER_CENTER = "UserCenter"; + + /// + /// 日志 + /// + public const string LOG_CENTER = "LogCenter"; + + /// + /// 系统中心 + /// + public const string SYSTEM_CENTER = "SystemCenter"; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Const/ClaimConst.cs b/src/Znyc.Dispatching.Core/Const/ClaimConst.cs new file mode 100644 index 0000000..2e32b33 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Const/ClaimConst.cs @@ -0,0 +1,35 @@ +namespace Znyc.Dispatching.Core +{ + public class ClaimConst + { + /// + /// 用户Id + /// + public const string CLAINM_USERID = "UserId"; + + /// + /// 账号 + /// + public const string CLAINM_ACCOUNT = "Account"; + + /// + /// 名称 + /// + public const string CLAINM_USERNAME = "UserName"; + + /// + /// 是否超级管理 + /// + public const string CLAINM_SUPERADMIN = "SuperAdmin"; + + /// + /// 角色Id + /// + public const string CLAINM_ROLEID = "RoleId"; + + /// + /// 公司Id + /// + public const string CLAINM_COMPANYID = "CompanyId"; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Const/CommonConst.cs b/src/Znyc.Dispatching.Core/Const/CommonConst.cs new file mode 100644 index 0000000..639a7ca --- /dev/null +++ b/src/Znyc.Dispatching.Core/Const/CommonConst.cs @@ -0,0 +1,233 @@ +namespace Znyc.Dispatching.Core +{ + public class CommonConst + { + /// + /// 默认密码 + /// + public const string DEFAULT_PASSWORD = "a123456"; + + /// + /// 默认超速速度 + /// + public const int DEFAULT_OVERSPEED = 80; + + /// + /// 默认停留标示Id + /// + public const long DEFAULT_STAPTAG = 1003; + + /// + /// 默认角色Id + /// + public const long DEFAULT_ROLEID_1001 = 1001; + + /// + /// 默认角色名称 + /// + public const string DEFAULT_ROLENAME_1001 = "车组人员"; + + /// + /// 车主人员默认首页路径 + /// + public const string DEFAULT_DRIVER_INDEX = "/pages/driverIndex/driverIndex"; + + + /// + /// 外租伙伴默认首页路径 + /// + public const string DEFAULT_OUTSIDE_INDEX = "/pages/follow_gzh/follow_gzh"; + + + /// + /// 管理员默认首页路径 + /// + public const string DEFAULT_SUPERADMIN_INDEX = "/map/pages/index/index"; + + /// + /// 默认加密盐 + /// + public const string DEFAULT_PASSWORD_SALT = "a4abd4acbdbdcc1c04b92735b6b22740"; + + /// + /// mongoDB超速报警表前缀 + /// + public const string DEFAULT_ALARMSTRAIGHT_PREFIX = "AlertStraightDtl_"; + + /// + /// 用户缓存 + /// + public const string CACHE_KEY_USER = "user_"; + + /// + /// 菜单缓存 + /// + public const string CACHE_KEY_MENU = "menu_"; + + /// + /// 权限缓存 + /// + public const string CACHE_KEY_PERMISSION = "permission_"; + + /// + /// 数据范围缓存 + /// + public const string CACHE_KEY_DATASCOPE = "datascope_"; + + /// + /// 验证码缓存 + /// + public const string CACHE_KEY_CODE = "vercode_"; + + /// + /// 角色缓存 + /// + public const string CACHE_KEY_ROLE = "rolelist"; + + /// + /// 角色菜单缓存 + /// + public const string CACHE_KEY_ROLEMENU = "rolemenulist_"; + + /// + /// 车辆类型缓存 + /// + public const string CACHE_KEY_VEHICLETYPE = "vehicletypelist"; + + /// + /// 车辆分组缓存 + /// + public const string CACHE_KEY_VEHICLEGROUP = "vehiclegroup_"; + + /// + /// 字典缓存 + /// + public const string CACHE_KEY_DICTIONARY = "dictionarylist"; + + /// + /// 默认logo地址 + /// + public const string DEFAULT_COMPANYLOG = "https://zhongnengyunche.com/dispatching/wx/upload/avatar/"; + + /// + /// 头像地址前缀 + /// + public const string Prefix_AvataUrl = "https://zhongnengyunche.com/dispatching/wx/upload/avatar/"; + + /// + /// 默认头像地址 + /// + public const string DEFAULT_AVATARURL = "Default_AvatarUrl.png"; + + /// + /// 默认头像全部地址 + /// + public const string DEFAULT_AVATARURL_ALL = "https://zhongnengyunche.com/dispatching/wx/upload/avatar/Default_AvatarUrl.png"; + + /// + /// 公司缓存 + /// + public const string CACHE_KEY_COMPANY = "company_"; + + /// + /// JWT + /// + public const string CACHE_KEY_JWT = "jwt_"; + + /// + /// token + /// + public const string CACHE_KEY_TOKEN = "token:{0}"; + + /// + /// 公司车辆缓存 + /// + public const string CACHE_KEY_VEHICLEBYCOMPANYID = "vehicles:company_"; + + /// + /// 车辆缓存 + /// + public const string CACHE_KEY_VEHICLE = "vehicle:_"; + + /// + /// 车辆GPS信息缓存 + /// + public const string CACHE_KEY_VEHICLEGPS = "vehiclegps_{0}:{1}"; + + /// + /// 超速记录缓存 + /// + public const string CACHE_KEY_VEHICLEALARM = "vehiclealarm_{0}:{1}:{2}"; + + /// + /// 员工缓存 + /// + public const string CACHE_KEY_EMPLOYEE = "employee:{0}"; + + /// + /// 员工列表缓存 + /// + public const string CACHE_KEY_EMPLOYEES = "employees:{0}"; + + /// + /// 未读报警消息 + /// + public const string CACHE_KEY_UNREADALARM = "unread:alarm:{0}"; + + /// + /// 轨迹回放 + /// + public const string CACHE_KEY_TRACKPLAYBACK = "vehicles:trackplayback_"; + + /// + /// 车场列表缓存 + /// + public const string CACHE_KEY_YARDS = "yards:{0}"; + + /// + /// 车场缓存 + /// + public const string CACHE_KEY_YARD = "yard:{0}"; + + #region 工程信息 + /// + /// 工程列表缓存 + /// + public const string CACHE_KEY_PROJECTS = "projects:{0}"; + + /// + /// 工程缓存 + /// + public const string CACHE_KEY_PROJECT = "project:{0}"; + #endregion + + /// + /// 车组人员缓存 + /// + public const string CACHE_KEY_VEHICLEPERSON = "vehicle:person:_"; + + #region 订单 + + /// + /// + /// + public const string CACHE_KEY_ORDERS = "orders:{0}"; + + /// + /// + /// + public const string CACHE_KEY_GPSREALTIME = "vehicle:gps_"; + + /// + /// 订单签证地址 + /// + public const string DEFAULT_ORDERVISA = "https://zhongnengyunche.com/dispatching/wx/upload/ordervisa/"; + + /// + /// + /// + public const string CACHE_KEY_ORDERREAD = "orderread_"; + #endregion + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Company.cs b/src/Znyc.Dispatching.Core/Entitys/Company.cs new file mode 100644 index 0000000..27adbaf --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Company.cs @@ -0,0 +1,106 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 公司表 + /// + [Table("dc_company")] + [Comment("公司表")] + public class Company : DEntityBase + { + /// + /// 公司名称 + /// + [Comment("公司名称")] + [Required] + [MaxLength(8)] + public string CompanyName { get; set; } + + /// + /// 公司Logo + /// + [Comment("公司Logo")] + public string CompanyLogo { get; set; } + + /// + /// 联系人 + /// + [Comment("联系人")] + [Required] + [MaxLength(30)] + public string ContactPerson { get; set; } + + /// + /// 联系人电话 + /// + [Comment("联系人电话")] + [Required] + [MaxLength(11)] + public string ContactPhone { get; set; } + + /// + /// 精度 + /// + [Comment("精度")] + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + [Comment("纬度")] + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + [Comment("地址")] + [MaxLength(35)] + public string Address { get; set; } + + /// + /// 审核时间 + /// + [Comment("审核时间")] + public DateTime AuditTime { get; set; } + + /// + /// 状态(字典 0正常 1停用 2删除) + /// + [Comment("状态")] + public int Status { get; set; } + + /// + /// 停留标示Id + /// + [Comment("停留标示Id")] + public long StopTag { get; set; } + + + /// + /// 一键派工是否显示工程名称 + /// + [Comment("一键派工是否显示工程名称")] + + public bool IsOpenDispatch { get; set; } + + + /// + /// 调度角色是否有添加工程名称的权限 + /// + [Comment("调度角色是否有添加工程名称的权限")] + + public bool IsSchedulingAddProject { get; set; } + + + /// + /// 是否启用任务车型选项,默认为关 + /// + [Comment("是否启用任务车型选项")] + + public bool IsOpenVehicleType { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Construction.cs b/src/Znyc.Dispatching.Core/Entitys/Construction.cs new file mode 100644 index 0000000..7e30f41 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Construction.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 施工单位表 + /// + [Table("dc_construction")] + [Comment("施工单位表")] + public class Construction : DEntityBase + { + + /// + /// 所属公司 + /// + public long CompanyId { get; set; } + + /// + /// 施工单位 + /// + public string ConstructionName { get; set; } + + /// + /// 联系人 + /// + public string ContactName { get; set; } + + /// + /// 联系电话 + /// + public string ContactPhone { get; set; } + + /// + /// 状态 + /// + public bool Status { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/DEntityBase.cs b/src/Znyc.Dispatching.Core/Entitys/DEntityBase.cs new file mode 100644 index 0000000..92b895e --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/DEntityBase.cs @@ -0,0 +1,76 @@ +using Furion.DatabaseAccessor; +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 自定义实体基类 + /// + public abstract class DEntityBase : DEntityBase + { + } + + public abstract class DEntityBase : DEntityBase + { + } + + public abstract class DEntityBase : PrivateDEntityBase + where TDbContextLocator1 : class, IDbContextLocator + { + } + + public abstract class DEntityBase : PrivateDEntityBase + where TDbContextLocator1 : class, IDbContextLocator + where TDbContextLocator2 : class, IDbContextLocator + { + } + + /// + /// 自定义实体基类 + /// + public abstract class PrivateDEntityBase : IPrivateEntity + { + /// + /// 主键Id + /// + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.None)] + [Comment("Id主键")] + public virtual long Id { get; set; } + + /// + /// 创建时间 + /// + [Comment("创建时间")] + public virtual DateTime CreatedTime { get; set; } + + /// + /// 更新时间 + /// + [Comment("更新时间")] + public virtual DateTime ModifiedTime { get; set; } + + /// + /// 创建者Id + /// + [Comment("创建者Id")] + public virtual long CreatedUserId { get; set; } + + /// + /// 修改者Id + /// + [Comment("修改者Id")] + public virtual long ModifiedUserId { get; set; } + + /// + /// 软删除 + /// + [JsonIgnore] + [Comment("软删除标记")] + public virtual bool IsDeleted { get; set; } = false; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Dictionary.cs b/src/Znyc.Dispatching.Core/Entitys/Dictionary.cs new file mode 100644 index 0000000..cf057e7 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Dictionary.cs @@ -0,0 +1,62 @@ +using Furion.DatabaseAccessor; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 数据字典表 + /// + [SuppressChangedListener] + [Table("dc_dictionary")] + [Comment("数据字典表")] + public class Dictionary : DEntityBase + { + /// + /// 字典父级 + /// + [Comment("字典父级")] + public long ParentId { get; set; } + + /// + /// 字典编码 + /// + [Comment("字典编码")] + [MaxLength(25)] + public string Code { get; set; } + + /// + /// 字典值 + /// + [Comment("字典值")] + [MaxLength(25)] + public string Value { get; set; } + + /// + /// 字典描述 + /// + [Comment("字典描述")] + [MaxLength(55)] + public string Description { get; set; } + + /// + /// 字典名称 + /// + [Comment("字典名称")] + [MaxLength(25)] + public string Name { get; set; } + + /// + /// 是否启用 + /// + [Comment("是否启用")] + public int IsEnabled { get; set; } + + /// + /// 字典排序 + /// + [Comment("字典排序")] + public int Sort { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Employee.cs b/src/Znyc.Dispatching.Core/Entitys/Employee.cs new file mode 100644 index 0000000..8b8864b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Employee.cs @@ -0,0 +1,78 @@ +using Furion.DatabaseAccessor; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 员工表 + /// + [SuppressChangedListener] + [Table("dc_employee")] + [Comment("员工表")] + public class Employee : DEntityBase + { + /// + /// 用户Id + /// + public long UserId { get; set; } + + /// + /// 员工头像 + /// + [Comment("员工头像")] + [MaxLength(125)] + public string AvatarUrl { get; set; } + + /// + /// 员工名 + /// + [Comment("员工名")] + public string EmployeeName { get; set; } + + /// + /// 手机号 + /// + [Comment("手机号")] + [MaxLength(11)] + public string EmployeePhone { get; set; } + + /// + /// 机构Id + /// + [Comment("所属公司")] + public long CompanyId { get; set; } + + ///// + ///// 机构名称 + ///// + ////[Comment("所属公司名称")] + ////[MaxLength(50)] + //public string CompanyName { get; set; } + + /// + /// CommonStatus + /// + [Comment("状态")] + public int Status { get; set; } + + /// + /// RoleStatus + /// + [Comment("角色")] + public long RoleId { get; set; } + + /// + /// RoleStatus + /// + [Comment("角色名称")] + public string RoleName { get; set; } + + /// + /// 是否默认登录 + /// + [Comment("是否默认登录")] + public bool IsDefault { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Job.cs b/src/Znyc.Dispatching.Core/Entitys/Job.cs new file mode 100644 index 0000000..7dd9bf9 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Job.cs @@ -0,0 +1,81 @@ +using Furion.TaskScheduler; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; + +namespace Dilon.Core +{ + /// + /// 定时任务 + /// + [Table("dc_job")] + [Comment("定时任务表")] + public class Job : DEntityBase + { + /// + /// 任务名称 + /// + /// dilon + [Comment("任务名称")] + public string JobName { get; set; } + + /// + /// 执行间隔时间(单位秒) + /// + /// 5 + [Comment("间隔时间")] + public int? Interval { get; set; } = 5; + + /// + /// Cron表达式 + /// + /// + [Comment("Cron表达式")] + public string Cron { get; set; } + + /// + /// 定时器类型 + /// + [Comment("定时器类型")] + public SpareTimeTypes TimerType { get; set; } = SpareTimeTypes.Interval; + + /// + /// 执行次数 + /// + [Comment("执行次数")] + public int? RunNumber { get; set; } + + /// + /// 请求url + /// + [Comment("请求url")] + public string RequestUrl { get; set; } + + /// + /// 请求参数(Post,Put请求用) + /// + [Comment("请求参数")] + public string RequestParameters { get; set; } + + /// + /// Headers(可以包含如:Authorization授权认证) + /// 格式:{"Authorization":"userpassword.."} + /// + [Comment("Headers")] + public string Headers { get; set; } + + /// + /// 请求类型 + /// + /// 2 + [Comment("请求类型")] + public RequestTypeEnum RequestType { get; set; } = RequestTypeEnum.Post; + + /// + /// 备注 + /// + [Comment("备注")] + public string Remark { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/LogAudit.cs b/src/Znyc.Dispatching.Core/Entitys/LogAudit.cs new file mode 100644 index 0000000..102d7a3 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/LogAudit.cs @@ -0,0 +1,61 @@ +using Furion.DatabaseAccessor; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 系统操作/审计日志表 + /// + [SuppressChangedListener] + [Table("dc_log_audit")] + [Comment("审计日志表")] + public class LogAudit : DEntityBase + { + /// + /// 表名 + /// + [Comment("表名")] + [MaxLength(50)] + public string TableName { get; set; } + + /// + /// 列名 + /// + [Comment("列名")] + [MaxLength(50)] + public string ColumnName { get; set; } + + /// + /// 新值 + /// + [Comment("新值")] + public string NewValue { get; set; } + + /// + /// 旧值 + /// + [Comment("旧值")] + public string OldValue { get; set; } + + /// + /// 操作人Id + /// + [Comment("操作人Id")] + public long UserId { get; set; } + + /// + /// 操作人名称 + /// + [Comment("操作人名称")] + [MaxLength(20)] + public string UserName { get; set; } + + /// + /// 操作方式:新增、更新、删除 + /// + [Comment("操作方式")] + public string Operate { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/LogEx.cs b/src/Znyc.Dispatching.Core/Entitys/LogEx.cs new file mode 100644 index 0000000..7d0f5c9 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/LogEx.cs @@ -0,0 +1,81 @@ +using Furion.DatabaseAccessor; +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 异常日志 + /// + [SuppressChangedListener] + [Table("dc_log_ex")] + [Comment("异常日志表")] + public class LogEx : DEntityBase + { + /// + /// 操作人 + /// + [Comment("操作人")] + [MaxLength(20)] + public string Account { get; set; } + + /// + /// 名称 + /// + [Comment("名称")] + [MaxLength(100)] + public string Name { get; set; } + + /// + /// 类名 + /// + [Comment("类名")] + [MaxLength(100)] + public string ClassName { get; set; } + + /// + /// 方法名 + /// + [Comment("方法名")] + [MaxLength(100)] + public string MethodName { get; set; } + + /// + /// 异常名称 + /// + [Comment("异常名称")] + public string ExceptionName { get; set; } + + /// + /// 异常信息 + /// + [Comment("异常信息")] + public string ExceptionMsg { get; set; } + + /// + /// 异常源 + /// + [Comment("异常源")] + public string ExceptionSource { get; set; } + + /// + /// 堆栈信息 + /// + [Comment("堆栈信息")] + public string StackTrace { get; set; } + + /// + /// 参数对象 + /// + [Comment("参数对象")] + public string ParamsObj { get; set; } + + /// + /// 异常时间 + /// + [Comment("异常时间")] + public DateTime ExceptionTime { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/LogOp.cs b/src/Znyc.Dispatching.Core/Entitys/LogOp.cs new file mode 100644 index 0000000..e06456b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/LogOp.cs @@ -0,0 +1,123 @@ +using Furion.DatabaseAccessor; +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 操作日志表 + /// + [SuppressChangedListener] + [Table("dc_log_op")] + [Comment("操作日志表")] + public class LogOp : DEntityBase + { + /// + /// 名称 + /// + [Comment("名称")] + [MaxLength(100)] + public string Name { get; set; } + + /// + /// 是否执行成功(Y-是,N-否) + /// + [Comment("是否执行成功")] + public YesOrNotEnum Success { get; set; } + + /// + /// 具体消息 + /// + [Comment("具体消息")] + public string Message { get; set; } + + /// + /// IP + /// + [Comment("IP")] + [MaxLength(20)] + public string Ip { get; set; } + + /// + /// 地址 + /// + [Comment("地址")] + [MaxLength(500)] + public string Location { get; set; } + + /// + /// 浏览器 + /// + [Comment("浏览器")] + [MaxLength(100)] + public string Browser { get; set; } + + /// + /// 操作系统 + /// + [Comment("操作系统")] + [MaxLength(100)] + public string Os { get; set; } + + /// + /// 请求地址 + /// + [Comment("请求地址")] + [MaxLength(100)] + public string Url { get; set; } + + /// + /// 类名称 + /// + [Comment("类名称")] + [MaxLength(100)] + public string ClassName { get; set; } + + /// + /// 方法名称 + /// + [Comment("方法名称")] + [MaxLength(100)] + public string MethodName { get; set; } + + /// + /// 请求方式(GET POST PUT DELETE) + /// + [Comment("请求方式")] + [MaxLength(10)] + public string ReqMethod { get; set; } + + /// + /// 请求参数 + /// + [Comment("请求参数")] + public string Param { get; set; } + + /// + /// 返回结果 + /// + [Comment("返回结果")] + public string Result { get; set; } + + /// + /// 耗时(毫秒) + /// + [Comment("耗时")] + public long ElapsedTime { get; set; } + + /// + /// 操作时间 + /// + [Comment("操作时间")] + public DateTime OpTime { get; set; } + + /// + /// 操作人 + /// + [Comment("操作人")] + [MaxLength(20)] + public string Account { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/LogVis.cs b/src/Znyc.Dispatching.Core/Entitys/LogVis.cs new file mode 100644 index 0000000..0662e65 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/LogVis.cs @@ -0,0 +1,83 @@ +using Furion.DatabaseAccessor; +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 访问日志表 + /// + [SuppressChangedListener] + [Table("dc_log_vis")] + [Comment("访问日志表")] + public class LogVis : DEntityBase + { + /// + /// 名称 + /// + [Comment("名称")] + [MaxLength(100)] + public string Name { get; set; } + + /// + /// 是否执行成功(Y-是,N-否) + /// + [Comment("是否执行成功")] + public YesOrNotEnum Success { get; set; } + + /// + /// 具体消息 + /// + [Comment("具体消息")] + public string Message { get; set; } + + /// + /// IP + /// + [Comment("IP")] + [MaxLength(20)] + public string Ip { get; set; } + + /// + /// 地址 + /// + [Comment("地址")] + [MaxLength(100)] + public string Location { get; set; } + + /// + /// 浏览器 + /// + [Comment("浏览器")] + [MaxLength(100)] + public string Browser { get; set; } + + /// + /// 操作系统 + /// + [Comment("操作系统")] + [MaxLength(100)] + public string Os { get; set; } + + /// + /// 访问类型 + /// + [Comment("访问类型")] + public LoginTypeEnum VisType { get; set; } + + /// + /// 访问时间 + /// + [Comment("访问时间")] + public DateTime VisTime { get; set; } + + /// + /// 访问人 + /// + [Comment("访问人")] + [MaxLength(20)] + public string Account { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Menu.cs b/src/Znyc.Dispatching.Core/Entitys/Menu.cs new file mode 100644 index 0000000..ffd3338 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Menu.cs @@ -0,0 +1,145 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 菜单表 + /// + [Table("dc_menu")] + [Comment("菜单表")] + public class Menu : DEntityBase + { + /// + /// 父Id + /// + [Comment("父Id")] + public long ParentId { get; set; } + + /// + /// 所属层级 + /// + [Comment("所属层级")] + public int Layers { get; set; } + + /// + /// 名称 + /// + [Comment("名称")] + [Required] + [MaxLength(20)] + public string Name { get; set; } + + /// + /// 编码 + /// + [Comment("编码")] + [Required] + [MaxLength(50)] + public string Code { get; set; } + + /// + /// 菜单类型(字典 0目录 1菜单 2按钮) + /// + [Comment("菜单类型")] + public MenuTypeEnum Type { get; set; } + + /// + /// 图标 + /// + [Comment("图标")] + [MaxLength(20)] + public string Icon { get; set; } + + /// + /// 路由地址 + /// + [Comment("路由地址")] + [MaxLength(100)] + public string Router { get; set; } + + /// + /// 权限标识 + /// + [Comment("权限标识")] + public string Permission { get; set; } + + /// + /// 是否外链 + /// + [Comment("是否外链")] + [MaxLength(5)] + public bool IsFrame { get; set; } + + /// + /// 是否展开 + /// + [Comment("是否展开")] + [MaxLength(5)] + public bool IsExpand { get; set; } + + /// + /// 是否显示 + /// + [Comment("是否显示")] + [MaxLength(5)] + public bool IsShow { get; set; } + + /// + /// 排序 + /// + [Comment("排序")] + public int Sort { get; set; } + + /// + /// 详细描述 + /// + [Comment("详细描述")] + [MaxLength(100)] + public string Description { get; set; } + + /// + /// CommonStatus + /// + public CommonStatusEnum Status { get; set; } = CommonStatusEnum.ENABLE; + + /// + /// 多对多(角色) + /// + public ICollection Roles { get; set; } + + /// + /// 多对多中间表(用户角色) + /// + public List RoleMenus { get; set; } + + /// + /// 上级 + /// + public virtual Menu Parent { get; set; } + + /// + /// 子集 + /// + public virtual ICollection Childrens { get; set; } + + /// + /// 配置实体关系 + /// + /// + /// + /// + public void Configure(EntityTypeBuilder entityBuilder, DbContext dbContext, Type dbContextLocator) + { + entityBuilder + .HasMany(x => x.Childrens) + .WithOne(x => x.Parent) + .HasForeignKey(x => x.ParentId) + .OnDelete(DeleteBehavior.ClientSetNull); // 必须设置这一行 + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Message.cs b/src/Znyc.Dispatching.Core/Entitys/Message.cs new file mode 100644 index 0000000..f7f01aa --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Message.cs @@ -0,0 +1,58 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 站内消息表 + /// + [Table("dc_message")] + [Comment("站内消息表")] + public class Message : DEntityBase + { + /// + /// 发送者Id + /// + [Comment("发送者Id")] + public long SendId { get; set; } + + /// + /// 消息标题 + /// + [Comment("消息标题")] + [Required] + [MaxLength(12)] + public string MessageTitle { get; set; } + + /// + /// 消息类型 + /// + [Comment("产品类型")] + public int MessageType { get; set; } + + /// + /// 发送类型 + /// + [Comment("发送类型")] + public int Type { get; set; } + + /// + /// 组Id + /// + public int GroupId { get; set; } + + /// + /// 消息内容 + /// + [Comment("消息内容")] + public string Content { get; set; } + + /// + /// 发送时间 + /// + [Comment("发送时间")] + public DateTime SendTime { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/MessageRecord.cs b/src/Znyc.Dispatching.Core/Entitys/MessageRecord.cs new file mode 100644 index 0000000..9317de1 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/MessageRecord.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 消息记录表 + /// + [Table("dc_message_record")] + [Comment("消息记录表")] + public class MessageRecord : DEntityBase + { + /// + /// 接收者Id + /// + [Comment("接收者Id")] + public long ReceiverId { get; set; } + + /// + /// 消息Id + /// + [Comment("消息Id")] + public long MessageId { get; set; } + + /// + /// 状态 + /// + [Comment("状态")] + public int Status { get; set; } + + /// + /// 站内消息 + /// + [Comment("站内消息")] + public Message Message { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Oil.cs b/src/Znyc.Dispatching.Core/Entitys/Oil.cs new file mode 100644 index 0000000..71242f1 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Oil.cs @@ -0,0 +1,55 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 油耗表 + /// + [Table("dc_oil")] + [Comment("油耗表")] + public class Oil : DEntityBase + { + /// + /// 公司Id + /// + public long CompanyId { get; set; } + + /// + /// 加油日期 + /// + public DateTime PlusOilDate { get; set; } + + /// + /// 车辆Id + /// + public long VehicleId { get; set; } + + /// + /// 车俩编号 + /// + public string VehicleCode { get; set; } + + /// + /// 加油单号 + /// + public string PlusOilOrder { get; set; } + + /// + /// 加油量 + /// + public string PlusOilAmount { get; set; } + + /// + /// 油单价 + /// + public decimal OilPrice { get; set; } + + /// + /// 金额 + /// + public decimal AmountMoney { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Order.cs b/src/Znyc.Dispatching.Core/Entitys/Order.cs new file mode 100644 index 0000000..7edf4bd --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Order.cs @@ -0,0 +1,164 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 派工订单表 + /// + [Table("dc_order")] + [Comment("派工订单表")] + public class Order : DEntityBase + { + + /// + /// 公司Id + /// + public long CompanyId { get; set; } + + /// + /// 车辆Id,,冗余查询车辆列表状态 + /// + public long VehicleId { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 到场时间 + /// + public DateTime ArriveDate { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// 状态,10=待指派,20=已指派,未接单,30=已接单,40=已出发,50=已完成,60=已签单,70=已离开,80=已评价,101=撤销 + /// + public int Status { get; set; } + + /// + /// 工程Id + /// + public long ProjectId { get; set; } + + /// + /// 工程名称 + /// + public string ProjectName { get; set; } + + /// + /// 业务员Id + /// + public long SalesmanId { get; set; } + + /// + /// 订单来源,10=录入,20=报单 + /// + public int OrderSource { get; set; } + + /// + /// 订单内容 + /// + public string OrderContent { get; set; } + + /// + /// 是否外请车 + /// + public bool IsOutside { get; set; } + + /// + /// 指派时间 + /// + public DateTime? AssignDate { get; set; } + + + /// + /// 指派人 + /// + public long AssignUserId { get; set; } + + /// + /// 接单时间 + /// + public DateTime? ReceiveDate { get; set; } + + /// + /// 出发时间 + /// + public DateTime? TravelDate { get; set; } + + /// + /// 到达时间 + /// + public DateTime? AppearDate { get; set; } + + /// + /// 签单时间 + /// + public DateTime? SignDate { get; set; } + /// + /// 完成时间 + /// + public DateTime? CompleteDate { get; set; } + + /// + /// 评价时间 + /// + public DateTime? EvaluateDate { get; set; } + + /// + /// 离开时间 + /// + public DateTime? LeaveDate { get; set; } + + + /// + /// 到家时间 + /// + public DateTime? ArriveHomeDate { get; set; } + + + /// + /// 车组人员 + /// + public string OrderVehiclePerson { get; set; } + + + + /// + /// 任务车型 + /// + public long VehicleType { get; set; } + + /// + /// 施工单位 + /// + public long ConstructionId { get; set; } + + + + + /// + /// 承租公司 + /// + //public long TenantCompanyId { get; set; } + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/OrderVehicle.cs b/src/Znyc.Dispatching.Core/Entitys/OrderVehicle.cs new file mode 100644 index 0000000..692d5d8 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/OrderVehicle.cs @@ -0,0 +1,43 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 派工订单车组人员表 + /// + [Table("dc_order_vehicle")] + [Comment("派工订单车组人员表")] + public class OrderVehicle : DEntityBase + { + + /// + /// 订单Id + /// + public long OrderId { get; set; } + + + /// + /// 指派任务人员Id + /// + public long UserId { get; set; } + + /// + /// 姓名 + /// + public string UserName { get; set; } + + + /// + /// 电话 + /// + public string UserPhone { get; set; } + + /// + /// 是否司机 + /// + public bool IsDriver { get; set; } + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/OrderVisa.cs b/src/Znyc.Dispatching.Core/Entitys/OrderVisa.cs new file mode 100644 index 0000000..7ecab98 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/OrderVisa.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 订单签证表 + /// + [Table("dc_order_visa")] + [Comment("订单签证表")] + public class OrderVisa : DEntityBase + { + + /// + /// 订单Id + /// + public long OrderId { get; set; } + + + + /// + /// 图片路径 + /// + public string Picture { get; set; } + + + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Project.cs b/src/Znyc.Dispatching.Core/Entitys/Project.cs new file mode 100644 index 0000000..a10c76b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Project.cs @@ -0,0 +1,64 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 工程信息表 + /// + [Table("dc_project")] + [Comment("工程信息表")] + public class Project : DEntityBase + { + + /// + /// 所属公司 + /// + public long CompanyId { get; set; } + + /// + /// 工程名称 + /// + public string ProjectName { get; set; } + + /// + /// 业务员Id + /// + public long SalesmanId { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + + /// + /// 是否启用 + /// + public bool IsEnabled { get; set; } + + + #region v1.2.7 + /// + /// 施工单位 + /// + public long ConstructionId { get; set; } + + + /// + /// 施工单位名称 + /// + public string ConstructionName { get; set; } + #endregion + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/ProjectPerson.cs b/src/Znyc.Dispatching.Core/Entitys/ProjectPerson.cs new file mode 100644 index 0000000..d7e4bf9 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/ProjectPerson.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 工程信息联系人表 + /// + [Table("dc_project_person")] + [Comment("工程信息联系人表")] + public class ProjectPerson : DEntityBase + { + /// + /// 工程Id + /// + public long ProjectId { get; set; } + + /// + /// 联系人Id,链接员工表Id + /// + public long ProjectPersonId { get; set; } + + /// + /// 联系人姓名 + /// + public string ProjectPersonName { get; set; } + + /// + /// 联系人电话 + /// + public string ProjectPersonPhone { get; set; } + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Report.cs b/src/Znyc.Dispatching.Core/Entitys/Report.cs new file mode 100644 index 0000000..099fd21 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Report.cs @@ -0,0 +1,50 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 意见反馈表 + /// + [Table("dc_report")] + [Comment("意见反馈表")] + public class Report : DEntityBase + { + /// + /// 投诉人Id + /// + [Comment("投诉人Id")] + public long ReportUserId { get; set; } + + /// + /// 投诉内容 + /// + [Comment("投诉内容")] + public string ReportContent { get; set; } + + /// + /// 投诉时间 + /// + [Comment("投诉时间")] + public DateTime ReportTime { get; set; } + + /// + /// 举报状态 + /// + [Comment("举报状态")] + public int ReportStatus { get; set; } + + /// + /// 处理状态 + /// + [Comment("处理状态")] + public int HandleStatus { get; set; } + + /// + /// 处理结果 + /// + [Comment("处理结果")] + public string Note { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Role.cs b/src/Znyc.Dispatching.Core/Entitys/Role.cs new file mode 100644 index 0000000..83ddbcb --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Role.cs @@ -0,0 +1,43 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 角色表 + /// + [Table("dc_role")] + [Comment("角色表")] + public class Role : DEntityBase + { + /// + /// 名称 + /// + [Comment("名称")] + [Required] + [MaxLength(10)] + public string Name { get; set; } + + /// + /// 编码 + /// + [Comment("父级权限Id")] + [Required] + public long ParentId { get; set; } + + /// + /// 角色说明 + /// + [Comment("角色说明")] + public string Intro { get; set; } + + /// + /// 状态(字典 0正常 1停用 2删除) + /// + [Comment("状态")] + public CommonStatusEnum Status { get; set; } = CommonStatusEnum.ENABLE; + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/RoleMenu.cs b/src/Znyc.Dispatching.Core/Entitys/RoleMenu.cs new file mode 100644 index 0000000..9760578 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/RoleMenu.cs @@ -0,0 +1,26 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 角色菜单表 + /// + [Table("dc_role_menu")] + [Comment("角色菜单表")] + public class RoleMenu : DEntityBase + { + /// + /// 角色Id + /// + [Comment("角色Id")] + public long RoleId { get; set; } + + /// + /// 菜单Id + /// + [Comment("菜单Id")] + public long MenuId { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Salesman.cs b/src/Znyc.Dispatching.Core/Entitys/Salesman.cs new file mode 100644 index 0000000..fc6eaf2 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Salesman.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 业务员 + /// + [Table("dc_salesman")] + [Comment("业务员息表")] + public class Salesman : DEntityBase + { + /// + /// 业务员姓名 + /// + public string SalesmanName { get; set; } + + /// + /// 业务员电话 + /// + public long SalesmanPhone { get; set; } + + /// + /// 是否启用 + /// + public bool IsEnabled { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/User.cs b/src/Znyc.Dispatching.Core/Entitys/User.cs new file mode 100644 index 0000000..e45d263 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/User.cs @@ -0,0 +1,49 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 用户表 + /// + [Table("dc_user")] + [Comment("用户表")] + public class User : DEntityBase + { + /// + /// OpenId + /// + [Comment("OpenId")] + [Required] + [MaxLength(32)] + public string OpenId { get; set; } + + /// + /// 头像 + /// + [Comment("头像")] + public string AvatarUrl { get; set; } + + /// + /// 用户名 + /// + [Comment("用户名")] + [MaxLength(38)] + public string UserName { get; set; } + + /// + /// 电话 + /// + [Comment("电话")] + [MaxLength(11)] + public string Phone { get; set; } + + /// + /// 状态 + /// + [Comment("状态")] + public CommonStatusEnum Status { get; set; } = CommonStatusEnum.ENABLE; + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/UserRole.cs b/src/Znyc.Dispatching.Core/Entitys/UserRole.cs new file mode 100644 index 0000000..a85db0b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/UserRole.cs @@ -0,0 +1,26 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 用户角色表 + /// + [Table("dc_user_role")] + [Comment("用户角色表")] + public class UserRole : DEntityBase + { + /// + /// 用户Id + /// + [Comment("用户Id")] + public long UserId { get; set; } + + /// + /// 系统角色Id + /// + [Comment("角色Id")] + public long RoleId { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/UserYard.cs b/src/Znyc.Dispatching.Core/Entitys/UserYard.cs new file mode 100644 index 0000000..8b9b561 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/UserYard.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 车场表 + /// + [Table("dc_user_yard")] + [Comment("用户车场映射表")] + public class UserYard : DEntityBase + { + /// + /// 用户Id + /// + [Comment("用户Id")] + public long UserId { get; set; } + + /// + /// 车场Id + /// + [Comment("车场Id")] + public long YardId { get; set; } + + /// + /// 公司Id + /// + [Comment("公司Id")] + public long CompanyId { get; set; } + + /// + /// 是否默认 + /// + [Comment("是否默认")] + public bool IsDefault { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Core/Entitys/Vehicle.cs b/src/Znyc.Dispatching.Core/Entitys/Vehicle.cs new file mode 100644 index 0000000..20f1b3c --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Vehicle.cs @@ -0,0 +1,180 @@ +using Furion.DataValidation; +using Microsoft.EntityFrameworkCore; +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 车辆表 + /// + [Table("dc_vehicle")] + [Comment("车辆表")] + public class Vehicle : DEntityBase + { + /// + /// 所属公司 + /// + [Comment("所属公司")] + public long CompanyId { get; set; } + + /// + /// 车辆编号 + /// + [Comment("车辆编号")] + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + [Comment("车牌号")] + public string VehiclePlate { get; set; } + + /// + /// 车辆类型 + /// + [Comment("车辆类型")] + public long VehicleType { get; set; } + + /// + /// 所属车组 + /// + [Comment("所属车组")] + public long VehicleGroup { get; set; } + + /// + /// SIM卡号 + /// + [Comment("SIM卡号")] + public string SimNo { get; set; } + + /// + /// 设备类型 + /// + [Comment("设备类型")] + public TerminalTypeEnum TerminalType { get; set; } = TerminalTypeEnum.BSJKGM_08; + + /// + /// 设备号 + /// + [Comment("设备号")] + public string TerminalNo { get; set; } + + /// + /// GPS协议号 + /// + [Comment("GPS协议号")] + public string AgreementNo { get; set; } + + /// + /// 是否激活 + /// + [Comment("是否激活")] + public bool IsActivate { get; set; } + + /// + /// 是否开启GPS + /// + [Comment("是否开启GPS")] + public bool IsGps { get; set; } + + /// + /// 所属司机 + /// + [Comment("所属司机")] + public long VehicleDriver { get; set; } + + /// + /// 司机电话 + /// + [Comment("司机电话")] + public string DriverPhone { get; set; } + + /// + /// 联系人 + /// + [Comment("联系人")] + public string ContactPerson { get; set; } + + /// + /// 联系电话 + /// + [Comment("联系电话")] + public string ContactPhone { get; set; } + + /// + /// IEML号 + /// + [Comment("IEML号")] + public string ImeiNo { get; set; } + + /// + /// 状态 + /// + [Comment("状态")] + public int Status { get; set; } + + /// + /// 打火状态 + /// + [Comment("打火状态")] + public int Acc { get; set; } + + /// + /// 工作状态 + /// + [Comment("工作状态")] + public int Work { get; set; } + + /// + /// Gps状态 + /// + [Comment("Gps状态")] + public int GpsState { get; set; } + + /// + /// GPS时间 + /// + [Comment("GPS时间")] + public DateTime? GpsTime { get; set; } + + /// + /// 开通时间 + /// + [Comment("开通时间")] + public DateTime OpenTime { get; set; } + + /// + /// 到期时间 + /// + [Comment("到期时间")] + public DateTime ExpireTime { get; set; } + + /// + /// 物联卡类型 + /// + [Comment("物联卡类型")] + public int CardType { get; set; } + + /// + /// 是否开启超速报警 + /// + [Comment("是否开启超速报警")] + public bool IsOverspeedAlarm { get; set; } + + /// + /// 超速速度 + /// + [Comment("超速速度")] + [DataValidation(ValidationTypes.PositiveNumber)] + public int Overspeed { get; set; } + + + /// + /// 排序 + /// + [Comment("排序字段")] + public int Sort { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/VehicleGroup.cs b/src/Znyc.Dispatching.Core/Entitys/VehicleGroup.cs new file mode 100644 index 0000000..e7889d5 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/VehicleGroup.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 车辆表分组 + /// + [Table("dc_vehicle_group")] + [Comment("车辆表分组")] + public class VehicleGroup : DEntityBase + { + /// + /// 公司Id + /// + [Comment("公司Id")] + public long CompanyId { get; set; } + + /// + /// 名称 + /// + [Comment("名称")] + public string Name { get; set; } + + /// + /// 父级权限Id + /// + [Comment("父级权限Id")] + public long ParentId { get; set; } + + /// + /// 状态(字典 0正常 1停用 2删除) + /// + [Comment("状态")] + public CommonStatusEnum Status { get; set; } = CommonStatusEnum.ENABLE; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/VehiclePerson.cs b/src/Znyc.Dispatching.Core/Entitys/VehiclePerson.cs new file mode 100644 index 0000000..fabde1c --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/VehiclePerson.cs @@ -0,0 +1,46 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 车组人员信息表 + /// + [Table("dc_vehicle_person")] + [Comment("车组人员信息表")] + public class VehiclePerson : DEntityBase + { + + /// + /// 公司Id + /// + [Comment("车辆Id")] + public long VehicleId { get; set; } + + /// + /// 车组人员Id + /// + [Comment("车组人员Id")] + public long UserId { get; set; } + + + /// + /// 员工名 + /// + [Comment("员工名")] + public string UserName { get; set; } + + + /// + /// 手机号 + /// + [Comment("手机号")] + public string UserPhone { get; set; } + + /// + /// 是否司机 + /// + [Comment("是否司机")] + public bool IsDriver { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/VehicleType.cs b/src/Znyc.Dispatching.Core/Entitys/VehicleType.cs new file mode 100644 index 0000000..c85f2dd --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/VehicleType.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 车辆类型表 + /// + [Table("dc_vehicle_type")] + [Comment("车辆表")] + public class VehicleType : DEntityBase + { + + + /// + /// 公司Id + /// + public long CompanyId { get; set; } + /// + /// 名称 + /// + [Comment("名称")] + public string Name { get; set; } + + /// + /// 父级权限Id + /// + [Comment("父级权限Id")] + public long ParentId { get; set; } + + /// + /// 状态(字典 0正常 1停用 2删除) + /// + [Comment("状态")] + public bool Status { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/WxUserRelation.cs b/src/Znyc.Dispatching.Core/Entitys/WxUserRelation.cs new file mode 100644 index 0000000..fcbba4a --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/WxUserRelation.cs @@ -0,0 +1,45 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 微信中间表 + /// + [Table("dc_wxuserrelation")] + [Comment("微信中间表")] + public class WxUserRelation : DEntityBase + { + /// + /// UnionId + /// + [Comment("UnionId")] + [Required] + [MaxLength(32)] + public string UnionId { get; set; } + + /// + /// OpenId + /// + [Comment("OpenId")] + [Required] + [MaxLength(32)] + public string OpenId { get; set; } + + /// + /// 用户Id + /// + + [Comment("用户Id")] + public long UserId { get; set; } + + /// + /// 公众号OpenId + /// + + [Comment("公众号OpenId")] + [MaxLength(32)] + public string WxOfficialOpenId { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Entitys/Yard.cs b/src/Znyc.Dispatching.Core/Entitys/Yard.cs new file mode 100644 index 0000000..eb474a5 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Entitys/Yard.cs @@ -0,0 +1,58 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Znyc.Dispatching.Core.Entitys +{ + /// + /// 车场表 + /// + [Table("dc_yard")] + [Comment("车场表")] + public class Yard : DEntityBase + { + /// + /// 公司Id + /// + [Comment("公司Id")] + public long CompanyId { get; set; } + + /// + /// 联系人 + /// + [Comment("联系人")] + [MaxLength(30)] + public string ContactPerson { get; set; } + + /// + /// 联系人电话 + /// + [Comment("联系人电话")] + [MaxLength(11)] + public string ContactPhone { get; set; } + + /// + /// 精度 + /// + [Comment("精度")] + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + [Comment("纬度")] + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + [Comment("地址")] + public string Address { get; set; } + + /// + /// 状态(字典 1正常 0停用 -1删除) + /// + [Comment("状态")] + public int Status { get; set; } + } +} diff --git a/src/Znyc.Dispatching.Core/Enums/AccStatusEnum.cs b/src/Znyc.Dispatching.Core/Enums/AccStatusEnum.cs new file mode 100644 index 0000000..cf9a62a --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/AccStatusEnum.cs @@ -0,0 +1,20 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 打火状态 + /// + public enum AccStatusEnum + { + /// + /// 关闭 + /// + [Description("关闭")] CLOSE = 0, + + /// + /// 正常打火 + /// + [Description("正常打火")] NORMAL = 1 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/CommonStatusEnum.cs b/src/Znyc.Dispatching.Core/Enums/CommonStatusEnum.cs new file mode 100644 index 0000000..358bdeb --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/CommonStatusEnum.cs @@ -0,0 +1,30 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 公共状态 + /// + public enum CommonStatusEnum + { + /// + /// 正常 + /// + [Description("正常")] ENABLE = 1, + + /// + /// 停用 + /// + [Description("停用")] DISABLE = -1, + + /// + /// 删除 + /// + [Description("删除")] DELETED = -2, + + /// + /// 审核中 + /// + [Description("审核中")] REVIEW = 0 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/DataOpTypeEnum.cs b/src/Znyc.Dispatching.Core/Enums/DataOpTypeEnum.cs new file mode 100644 index 0000000..45f87a3 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/DataOpTypeEnum.cs @@ -0,0 +1,78 @@ +namespace Znyc.Dispatching.Core +{ + /// + /// 数据操作类型 + /// + public enum DataOpTypeEnum + { + /// + /// 其它 + /// + OTHER, + + /// + /// 增加 + /// + ADD, + + /// + /// 删除 + /// + DELETE, + + /// + /// 编辑 + /// + EDIT, + + /// + /// 更新 + /// + UPDATE, + + /// + /// 查询 + /// + QUERY, + + /// + /// 详情 + /// + DETAIL, + + /// + /// 树 + /// + TREE, + + /// + /// 导入 + /// + IMPORT, + + /// + /// 导出 + /// + EXPORT, + + /// + /// 授权 + /// + GRANT, + + /// + /// 强退 + /// + FORCE, + + /// + /// 清空 + /// + CLEAN, + + /// + /// 修改状态 + /// + CHANGE_STATUS + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/ErrorCode.cs b/src/Znyc.Dispatching.Core/Enums/ErrorCode.cs new file mode 100644 index 0000000..d2a5ec6 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/ErrorCode.cs @@ -0,0 +1,379 @@ +using Furion.FriendlyException; + +namespace Znyc.Dispatching.Core +{ + /// + /// 系统错误码 + /// + [ErrorCodeType] + public enum ErrorCode + { + /// + /// 用户名或密码不正确 + /// + [ErrorCodeItemMetadata("用户名或密码不正确")] D1000, + + /// + /// 非法操作!禁止删除自己 + /// + [ErrorCodeItemMetadata("非法操作,禁止删除自己")] D1001, + + /// + /// 记录不存在 + /// + [ErrorCodeItemMetadata("记录不存在")] D1002, + + /// + /// 账号已存在 + /// + [ErrorCodeItemMetadata("账号已存在")] D1003, + + /// + /// 旧密码不匹配 + /// + [ErrorCodeItemMetadata("旧密码输入错误")] D1004, + + /// + /// 测试数据禁止更改admin密码 + /// + [ErrorCodeItemMetadata("测试数据禁止更改用户【admin】密码")] + D1005, + + /// + /// 数据已存在 + /// + [ErrorCodeItemMetadata("数据已存在")] D1006, + + /// + /// 数据不存在或含有关联引用,禁止删除 + /// + [ErrorCodeItemMetadata("数据不存在或含有关联引用,禁止删除")] + D1007, + + /// + /// 禁止为管理员分配角色 + /// + [ErrorCodeItemMetadata("禁止为管理员分配角色")] D1008, + + /// + /// 重复数据或记录含有不存在数据 + /// + [ErrorCodeItemMetadata("重复数据或记录含有不存在数据")] + D1009, + + /// + /// 禁止为超级管理员角色分配权限 + /// + [ErrorCodeItemMetadata("禁止为超级管理员角色分配权限")] + D1010, + + /// + /// 非法数据 + /// + [ErrorCodeItemMetadata("非法数据")] D1011, + + /// + /// Id不能为空 + /// + [ErrorCodeItemMetadata("Id不能为空")] D1012, + + /// + /// 所属机构不在自己的数据范围内 + /// + [ErrorCodeItemMetadata("没有权限操作该数据")] D1013, + + /// + /// 禁止删除超级管理员 + /// + [ErrorCodeItemMetadata("禁止删除超级管理员")] D1014, + + /// + /// 禁止修改超级管理员状态 + /// + [ErrorCodeItemMetadata("禁止修改超级管理员状态")] D1015, + + /// + /// 没有权限 + /// + [ErrorCodeItemMetadata("没有权限")] D1016, + + /// + /// 账号已冻结 + /// + [ErrorCodeItemMetadata("账号已冻结")] D1017, + + /// + /// 验证码错误 + /// + [ErrorCodeItemMetadata("验证码错误")] D1018, + + /// + /// 账号不存在 + /// + [ErrorCodeItemMetadata("账号不存在")] D1019, + + /// + /// 公司审核中 + /// + [ErrorCodeItemMetadata("公司审核中")] D1020, + + /// + /// 验证码失效 + /// + [ErrorCodeItemMetadata("验证码失效")] D1021, + + /// + /// 新密码不一致 + /// + [ErrorCodeItemMetadata("新密码不一致")] D1022, + + /// + /// 父机构不存在 + /// + [ErrorCodeItemMetadata("父机构不存在")] D2000, + + /// + /// 当前机构Id不能与父机构Id相同 + /// + [ErrorCodeItemMetadata("当前机构Id不能与父机构Id相同")] + D2001, + + /// + /// 已有相同组织机构,编码或名称相同 + /// + [ErrorCodeItemMetadata("已有相同组织机构,编码或名称相同")] + D2002, + + /// + /// 没有权限操作机构 + /// + [ErrorCodeItemMetadata("没有权限操作机构")] D2003, + + /// + /// 该机构下有员工禁止删除 + /// + [ErrorCodeItemMetadata("该机构下有员工禁止删除")] D2004, + + /// + /// 附属机构下有员工禁止删除 + /// + [ErrorCodeItemMetadata("附属机构下有员工禁止删除")] + D2005, + + /// + /// 只能增加下级机构 + /// + [ErrorCodeItemMetadata("只能增加下级机构")] D2006, + + /// + /// 字典类型不存在 + /// + [ErrorCodeItemMetadata("字典类型不存在")] D3000, + + /// + /// 字典类型已存在 + /// + [ErrorCodeItemMetadata("字典类型已存在,名称或编码重复")] + D3001, + + /// + /// 字典类型下面有字典值禁止删除 + /// + [ErrorCodeItemMetadata("字典类型下面有字典值禁止删除")] + D3002, + + /// + /// 字典值已存在 + /// + [ErrorCodeItemMetadata("字典值已存在,名称或编码重复")] + D3003, + + /// + /// 字典值不存在 + /// + [ErrorCodeItemMetadata("字典值不存在")] D3004, + + /// + /// 字典状态错误 + /// + [ErrorCodeItemMetadata("字典状态错误")] D3005, + + /// + /// 菜单已存在 + /// + [ErrorCodeItemMetadata("菜单已存在")] D4000, + + /// + /// 路由地址为空 + /// + [ErrorCodeItemMetadata("路由地址为空")] D4001, + + /// + /// 打开方式为空 + /// + [ErrorCodeItemMetadata("打开方式为空")] D4002, + + /// + /// 权限标识格式为空 + /// + [ErrorCodeItemMetadata("权限标识格式为空")] D4003, + + /// + /// 权限标识格式错误 + /// + [ErrorCodeItemMetadata("权限标识格式错误")] D4004, + + /// + /// 权限不存在 + /// + [ErrorCodeItemMetadata("权限不存在")] D4005, + + /// + /// 父级菜单不能为当前节点,请重新选择父级菜单 + /// + [ErrorCodeItemMetadata("父级菜单不能为当前节点,请重新选择父级菜单")] + D4006, + + /// + /// 不能移动根节点 + /// + [ErrorCodeItemMetadata("不能移动根节点")] D4007, + + /// + /// 已存在同名或同编码应用 + /// + [ErrorCodeItemMetadata("已存在同名或同编码应用")] D5000, + + /// + /// 默认激活系统只能有一个 + /// + [ErrorCodeItemMetadata("默认激活系统只能有一个")] D5001, + + /// + /// 该应用下有菜单禁止删除 + /// + [ErrorCodeItemMetadata("该应用下有菜单禁止删除")] D5002, + + /// + /// 已存在同名或同编码应用 + /// + [ErrorCodeItemMetadata("已存在同名或同编码应用")] D5003, + + /// + /// 已存在同名或同编码职位 + /// + [ErrorCodeItemMetadata("已存在同名或同编码职位")] D6000, + + /// + /// 该职位下有员工禁止删除 + /// + [ErrorCodeItemMetadata("该职位下有员工禁止删除")] D6001, + + /// + /// 通知公告状态错误 + /// + [ErrorCodeItemMetadata("通知公告状态错误")] D7000, + + /// + /// 通知公告删除失败 + /// + [ErrorCodeItemMetadata("通知公告删除失败")] D7001, + + /// + /// 通知公告编辑失败 + /// + [ErrorCodeItemMetadata("通知公告编辑失败,类型必须为草稿")] + D7002, + + /// + /// 文件不存在 + /// + [ErrorCodeItemMetadata("文件不存在")] D8000, + + /// + /// 已存在同名或同编码参数配置 + /// + [ErrorCodeItemMetadata("已存在同名或同编码参数配置")] + D9000, + + /// + /// 禁止删除系统参数 + /// + [ErrorCodeItemMetadata("禁止删除系统参数")] D9001, + + /// + /// 已存在同名任务调度 + /// + [ErrorCodeItemMetadata("已存在同名任务调度")] D1100, + + /// + /// 任务调度不存在 + /// + [ErrorCodeItemMetadata("任务调度不存在")] D1101, + + /// + /// 演示环境禁止修改数据 + /// + [ErrorCodeItemMetadata("演示环境禁止修改数据")] D1200, + + /// + /// 已存在同名或同主机租户 + /// + [ErrorCodeItemMetadata("已存在同名或同主机租户")] D1300, + + /// + /// 该表代码模板已经生成过 + /// + [ErrorCodeItemMetadata("该表代码模板已经生成过")] D1400, + + /// + /// 该类型不存在 + /// + [ErrorCodeItemMetadata("该类型不存在")] D1501, + + /// + /// 该字段不存在 + /// + [ErrorCodeItemMetadata("该字段不存在")] D1502, + + /// + /// 该类型不是枚举类型 + /// + [ErrorCodeItemMetadata("该类型不是枚举类型")] D1503, + + /// + /// 该实体不存在 + /// + [ErrorCodeItemMetadata("该实体不存在")] D1504, + + /// + /// 父菜单不存在 + /// + [ErrorCodeItemMetadata("父菜单不存在")] D1505, + + /// + /// 已存在同名或同编码项目 + /// + [ErrorCodeItemMetadata("已存在同名或同编码项目")] xg1000, + + /// + /// 已存在相同证件号码人员 + /// + [ErrorCodeItemMetadata("已存在相同证件号码人员")] xg1001, + + /// + /// 检测数据不存在 + /// + [ErrorCodeItemMetadata("检测数据不存在")] xg1002, + + /// + /// JsCode不存在 + /// + [ErrorCodeItemMetadata("JsCode不存在")] D1506, + + /// + /// 账号已存在 + /// + [ErrorCodeItemMetadata("账号已存在")] xg1003 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/FileLocationEnum.cs b/src/Znyc.Dispatching.Core/Enums/FileLocationEnum.cs new file mode 100644 index 0000000..9faa223 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/FileLocationEnum.cs @@ -0,0 +1,30 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 文件存储位置 + /// + public enum FileLocationEnum + { + /// + /// 阿里云 + /// + [Description("阿里云")] ALIYUN = 1, + + /// + /// 腾讯云 + /// + [Description("腾讯云")] TENCENT = 2, + + /// + /// minio服务器 + /// + [Description("minio服务器")] MINIO = 3, + + /// + /// 本地 + /// + [Description("本地")] LOCAL = 4 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/GpsStatusEnum.cs b/src/Znyc.Dispatching.Core/Enums/GpsStatusEnum.cs new file mode 100644 index 0000000..fa00d8b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/GpsStatusEnum.cs @@ -0,0 +1,25 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// Gps状态 + /// + public enum GpsStatusEnum + { + /// + /// 离线 + /// + [Description("离线")] OFFLINE = 0, + + /// + /// 行驶 + /// + [Description("行驶")] DRIVING = 1, + + /// + /// 静止 + /// + [Description("静止")] STILL = 2 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/HangFireQueuesConfig.cs b/src/Znyc.Dispatching.Core/Enums/HangFireQueuesConfig.cs new file mode 100644 index 0000000..bf8168b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/HangFireQueuesConfig.cs @@ -0,0 +1,29 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core.Enums +{ + //HangFire定时任务相关 + public enum HangFireQueuesConfig + { + /// + /// 默认 + /// + [Description("默认")] + @default = 1, + /// + /// 接口 + /// + [Description("接口")] + apis = 2, + /// + /// 网站 + /// + [Description("网站")] + web = 3, + /// + /// 循环时间 + /// + [Description("循环时间")] + recurring = 4, + } +} diff --git a/src/Znyc.Dispatching.Core/Enums/HttpStatusCodeEnum.cs b/src/Znyc.Dispatching.Core/Enums/HttpStatusCodeEnum.cs new file mode 100644 index 0000000..856a76d --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/HttpStatusCodeEnum.cs @@ -0,0 +1,212 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// HTTP状态码 + /// + public enum HttpStatusCodeEnum + { + /// + /// 客户端可能继续其请求 + /// + [Description("继续")] Continue = 100, + + /// + /// 正在更改协议版本或协议 + /// + [Description("交换协议")] SwitchingProtocols = 101, + + /// + /// 请求成功,且请求的信息包含在响应中 + /// + [Description("OK")] OK = 200, + + /// + /// 请求导致在响应被发送前创建新资源 + /// + [Description("已创建")] Created = 201, + + /// + /// 请求已被接受做进一步处理 + /// + [Description("接收")] Accepted = 202, + + /// + /// 返回的元信息来自缓存副本而不是原始服务器,因此可能不正确 + /// + [Description("非认证信息")] NonAuthoritativeInformation = 203, + + /// + /// 已成功处理请求并且响应已被设定为无内容 + /// + [Description("无内容")] NoContent = 204, + + /// + /// 客户端应重置(或重新加载)当前资源 + /// + [Description("重置内容")] ResetContent = 205, + + /// + /// 响应是包括字节范围的 GET请求所请求的部分响应 + /// + [Description("部分内容")] PartialContent = 206, + + /// + /// 请求的信息有多种表示形式,默认操作是将此状态视为重定向 + /// + [Description("多路选择")] MultipleChoices = 300, + + /// + /// 请求的信息已移到 Location头中指定的 URI 处 + /// + [Description("永久转移")] MovedPermanently = 301, + + /// + /// 请求的信息位于 Location 头中指定的 URI 处 + /// + [Description("暂时转移")] Found = 302, + + /// + /// 将客户端自动重定向到 Location 头中指定的 URI + /// + [Description("参见其它")] SeeOther = 303, + + /// + /// 客户端的缓存副本是最新的 + /// + [Description("未修改")] NotModified = 304, + + /// + /// 请求应使用位于 Location 头中指定的 URI 的代理服务器 + /// + [Description("使用代理")] UseProxy = 305, + + /// + /// 服务器未能识别请求 + /// + [Description("错误请求")] BadRequest = 400, + + /// + /// 请求的资源要求身份验证 + /// + [Description("未认证")] Unauthorized = 401, + + /// + /// 需要付费 + /// + [Description("需要付费")] PaymentRequired = 402, + + /// + /// 服务器拒绝满足请求 + /// + [Description("禁止")] Forbidden = 403, + + /// + /// 请求的资源不在服务器上 + /// + [Description("未找到")] NotFound = 404, + + /// + /// 请求的资源上不允许请求方法(POST或 GET) + /// + [Description("请求方法不允许")] MethodNotAllowed = 405, + + /// + /// 客户端已用 Accept 头指示将不接受资源的任何可用表示形式 + /// + [Description("不接受")] NotAcceptable = 406, + + /// + /// 请求的代理要求身份验证 + /// Proxy-authenticate 头包含如何执行身份验证的详细信息 + /// + [Description("需要代理认证")] ProxyAuthenticationRequired = 407, + + /// + /// 客户端没有在服务器期望请求的时间内发送请求 + /// + [Description("请求超时")] RequestTimeout = 408, + + /// + /// 由于服务器上的冲突而未能执行请求 + /// + [Description("冲突")] Conflict = 409, + + /// + /// 请求的资源不再可用 + /// + [Description("失败")] Gone = 410, + + /// + /// 缺少必需的 Content-length + /// + [Description("缺少Content-length头")] LengthRequired = 411, + + /// + /// 为此请求设置的条件失败,且无法执行此请求 + /// 条件是用条件请求标头(如 If-Match、If-None-Match 或 If-Unmodified-Since)设置的。 + /// + [Description("条件失败")] PreconditionFailed = 412, + + /// + /// 请求太大,服务器无法处理 + /// + [Description("请求实体太大")] RequestEntityTooLarge = 413, + + /// + /// URI 太长 + /// + [Description("请求URI太长")] RequestUriTooLong = 414, + + /// + /// 请求是不支持的类型 + /// + [Description("不支持的媒体类型")] UnsupportedMediaType = 415, + + /// + /// 无法返回从资源请求的数据范围,因为范围的开头在资源的开头之前,或因为范围的结尾在资源的结尾之后 + /// + [Description("数据范围不匹配")] RequestedRangeNotSatisfiable = 416, + + /// + /// 服务器未能符合Expect头中给定的预期值 + /// + [Description("服务器与Expect头不匹配")] ExpectationFailed = 417, + + /// + /// 服务器拒绝处理客户端使用当前协议发送的请求,但是可以接受其使用升级后的协议发送的请求 + /// + [Description("当前协议不受支持")] UpgradeRequired = 426, + + /// + /// 服务器上发生了一般错误 + /// + [Description("服务器内部错误")] InternalServerError = 500, + + /// + /// 服务器不支持请求的函数 + /// + [Description("未实现")] NotImplemented = 501, + + /// + /// 中间代理服务器从另一代理或原始服务器接收到错误响应 + /// + [Description("网关失败")] BadGateway = 502, + + /// + /// 服务器暂时不可用,通常是由于过多加载或维护 + /// + [Description("服务器维护")] ServiceUnavailable = 503, + + /// + /// 中间代理服务器在等待来自另一个代理或原始服务器的响应时已超时 + /// + [Description("网关超时")] GatewayTimeout = 504, + + /// + /// 服务器不支持请求的HTTP版本 + /// + [Description("HTTP版本不支持")] HttpVersionNotSupported = 505 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/LoginTypeEnum.cs b/src/Znyc.Dispatching.Core/Enums/LoginTypeEnum.cs new file mode 100644 index 0000000..7d757a4 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/LoginTypeEnum.cs @@ -0,0 +1,35 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 登陆类型 + /// + public enum LoginTypeEnum + { + /// + /// 登陆 + /// + [Description("登陆")] LOGIN = 0, + + /// + /// 登出 + /// + [Description("登出")] LOGOUT = 1, + + /// + /// 注册 + /// + [Description("注册")] REGISTER = 2, + + /// + /// 改密 + /// + [Description("改密")] CHANGEPASSWORD = 3, + + /// + /// 三方授权登陆 + /// + [Description("授权登陆")] AUTHORIZEDLOGIN = 4 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/MenuTypeEnum.cs b/src/Znyc.Dispatching.Core/Enums/MenuTypeEnum.cs new file mode 100644 index 0000000..bbd0cea --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/MenuTypeEnum.cs @@ -0,0 +1,25 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 系统菜单类型 + /// + public enum MenuTypeEnum + { + /// + /// 目录 + /// + [Description("目录")] DIR = 0, + + /// + /// 菜单 + /// + [Description("菜单")] MENU = 1, + + /// + /// 按钮 + /// + [Description("按钮")] BTN = 2 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/NoticeUserStatusEnum.cs b/src/Znyc.Dispatching.Core/Enums/NoticeUserStatusEnum.cs new file mode 100644 index 0000000..53e9866 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/NoticeUserStatusEnum.cs @@ -0,0 +1,20 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 通知公告用户状态 + /// + public enum NoticeUserStatusEnum + { + /// + /// 未读 + /// + [Description("未读")] UNREAD = 0, + + /// + /// 已读 + /// + [Description("已读")] READ = 1 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/OrderSourceEnum.cs b/src/Znyc.Dispatching.Core/Enums/OrderSourceEnum.cs new file mode 100644 index 0000000..a6003cd --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/OrderSourceEnum.cs @@ -0,0 +1,24 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 派工订单来源 + /// + public enum OrderSourceEnum + { + /// + /// 录入 + /// + [Description("录入")] + Input = 10, + + /// + /// 报单 + /// + [Description("报单")] + Declaration = 20, + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/OrderStatus.cs b/src/Znyc.Dispatching.Core/Enums/OrderStatus.cs new file mode 100644 index 0000000..6beb44f --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/OrderStatus.cs @@ -0,0 +1,82 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 派工状态 + /// + public enum OrderStatus + { + + /// + /// 草稿 + /// + [Description("草稿")] + Draft = 0, + + /// + /// 待指派 + /// + [Description("待指派")] + StayAssign = 10, + + /// + /// 已指派(未接单) + /// + [Description("未接单")] + Assign = 20, + + /// + /// 已接单 + /// + [Description("已接单")] + Receive = 30, + + /// + /// 已出发 + /// + [Description("已出发")] + Travel = 40, + + /// + /// 已到达 + /// + [Description("已到达")] + Appear = 50, + + /// + /// 已完成 + /// + [Description("已完成")] + Complete = 60, + + /// + /// 已签单 + /// + [Description("已签单")] + Sign = 70, + /// + /// 已离开 + /// + [Description("已离开")] + Leave = 80, + + /// + /// 已评价 + /// + [Description("已评价")] + Evaluate = 90, + + /// + /// 撤销 + /// + [Description("撤销")] + Cancel = 101, + + /// + /// 已到家 + /// + [Description("已到家")] + ArriveHome = 85, + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/PlatformTypeEnum.cs b/src/Znyc.Dispatching.Core/Enums/PlatformTypeEnum.cs new file mode 100644 index 0000000..bb0c038 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/PlatformTypeEnum.cs @@ -0,0 +1,22 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + public enum PlatformTypeEnum + { + /// + /// 人才招聘 + /// + [Description("人才招聘")] Recruitment = 1, + + /// + /// 派工调度 + /// + [Description("派工调度")] Dispatching = 2, + + /// + /// 后台管理系统 + /// + [Description("后台管理系统")] Management = 3 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/QueryTypeEnum.cs b/src/Znyc.Dispatching.Core/Enums/QueryTypeEnum.cs new file mode 100644 index 0000000..826d18f --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/QueryTypeEnum.cs @@ -0,0 +1,50 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 查询类型的枚举 + /// + public enum QueryTypeEnum + { + /// + /// 等于 + /// + [Description("等于")] eq = 0, + + /// + /// 模糊 + /// + [Description("模糊")] like = 1, + + /// + /// 大于 + /// + [Description("大于")] gt = 2, + + /// + /// 小于 + /// + [Description("小于")] lt = 3, + + /// + /// 不等于 + /// + [Description("不等于")] ne = 4, + + /// + /// 大于等于 + /// + [Description("大于等于")] ge = 5, + + /// + /// 小于等于 + /// + [Description("小于等于")] le = 6, + + /// + /// 不为空 + /// + [Description("不为空")] isNotNull = 7 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/RequestTypeEnum.cs b/src/Znyc.Dispatching.Core/Enums/RequestTypeEnum.cs new file mode 100644 index 0000000..d546835 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/RequestTypeEnum.cs @@ -0,0 +1,33 @@ +namespace Znyc.Dispatching.Core +{ + /// + /// http请求类型 + /// + public enum RequestTypeEnum + { + /// + /// 执行内部方法 + /// + Run = 0, + + /// + /// GET请求 + /// + Get = 1, + + /// + /// POST请求 + /// + Post = 2, + + /// + /// PUT请求 + /// + Put = 3, + + /// + /// DELETE请求 + /// + Delete = 4 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/RoleStatusEnum.cs b/src/Znyc.Dispatching.Core/Enums/RoleStatusEnum.cs new file mode 100644 index 0000000..242fca9 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/RoleStatusEnum.cs @@ -0,0 +1,65 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 角色类型 + /// + public enum RoleStatusEnum + { + /// + /// 车组人员 + /// + [Description("车组人员")] CrewMembers = 1001, + + /// + /// 调度 + /// + [Description("调度")] Scheduling = 1002, + + /// + /// 销售 + /// + [Description("销售")] Sales = 1003, + + /// + /// 财务 + /// + [Description("财务")] Financial = 1004, + + /// + /// 管理员 + /// + [Description("管理员")] Administrator = 1005, + + /// + /// 业务员 + /// + [Description("业务员")] Salesman = 1006, + + /// + /// 车队长 + /// + [Description("车队长")] CarCaptain = 1007, + + /// + /// 仓管 + /// + [Description("仓管")] WareHouse = 1008, + + /// + /// 工地施工员 + /// + [Description("工地施工员")] ProjectPerson = 1009, + + /// + /// 外租伙伴 + /// + [Description("外租伙伴")] Outside = 1010, + + /// + /// 兼职业务 + /// + [Description("兼职业务")] PartTimeSalesman = 1011, + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/StopStatusEnum.cs b/src/Znyc.Dispatching.Core/Enums/StopStatusEnum.cs new file mode 100644 index 0000000..90cd5d2 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/StopStatusEnum.cs @@ -0,0 +1,25 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 停留点状态 + /// + public enum StopStatusEnum + { + /// + /// 起点 + /// + [Description("起点")] STARTPOINT = 0, + + /// + /// 停留点 + /// + [Description("停留点")] STOPPOINT = 1, + + /// + /// 终点 + /// + [Description("终点")] ENDPOINT = 3 + } +} diff --git a/src/Znyc.Dispatching.Core/Enums/TerminalTypeEnum.cs b/src/Znyc.Dispatching.Core/Enums/TerminalTypeEnum.cs new file mode 100644 index 0000000..6a92eca --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/TerminalTypeEnum.cs @@ -0,0 +1,15 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 产品类型 + /// + public enum TerminalTypeEnum + { + /// + /// 博实结KG_M08四线 + /// + [Description("博实结KG_M08四线")] BSJKGM_08 = 1 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/WorkStatusEnum.cs b/src/Znyc.Dispatching.Core/Enums/WorkStatusEnum.cs new file mode 100644 index 0000000..c701cac --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/WorkStatusEnum.cs @@ -0,0 +1,20 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 工作状态 + /// + public enum WorkStatusEnum + { + /// + /// 关闭 + /// + [Description("关闭")] CLOSE = 0, + + /// + /// 正常工作 + /// + [Description("正常工作")] NORMAL = 1 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Enums/YesOrNotEnum.cs b/src/Znyc.Dispatching.Core/Enums/YesOrNotEnum.cs new file mode 100644 index 0000000..56e0eab --- /dev/null +++ b/src/Znyc.Dispatching.Core/Enums/YesOrNotEnum.cs @@ -0,0 +1,20 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 菜单激活类型 + /// + public enum YesOrNotEnum + { + /// + /// 是 + /// + [Description("是")] Y = 0, + + /// + /// 否 + /// + [Description("否")] N = 1 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Extension/DateTimeExtensions.cs b/src/Znyc.Dispatching.Core/Extension/DateTimeExtensions.cs new file mode 100644 index 0000000..8e9907b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Extension/DateTimeExtensions.cs @@ -0,0 +1,36 @@ +using System; + +namespace Znyc.Dispatching.Core +{ + public static class DateTimeExtensions + { + /// + /// 时间戳起始日期 + /// + public static DateTime TimestampStart = new(1970, 1, 1, 0, 0, 0, 0); + + /// + /// 转换为时间戳 + /// + /// + /// 是否使用毫秒 + /// + public static int ToTimestamp(this DateTime dateTime, bool milliseconds = false) + { + TimeSpan timestamp = dateTime.ToUniversalTime() - TimestampStart; + return (int)(milliseconds ? timestamp.TotalMilliseconds : timestamp.TotalSeconds); + } + + /// + /// 获取周几 + /// + /// + /// + public static string GetWeekName(this DateTime datetime) + { + int day = (int)datetime.DayOfWeek; + string[] week = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; + return week[day]; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Extension/DictionaryExtensions.cs b/src/Znyc.Dispatching.Core/Extension/DictionaryExtensions.cs new file mode 100644 index 0000000..7f1b5c0 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Extension/DictionaryExtensions.cs @@ -0,0 +1,52 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web; + +namespace Znyc.Dispatching.Core +{ + /// + /// 字典扩展 + /// + public static class DictionaryExtensions + { + /// + /// 将一个字典转化为 QueryString + /// + /// + /// + /// + public static string ToQueryString(this Dictionary dict, bool urlEncode = true) + { + return string.Join("&", + dict.Select(p => $"{(urlEncode ? p.Key?.UrlEncode() : "")}={(urlEncode ? p.Value?.UrlEncode() : "")}")); + } + + /// + /// 将一个字符串 URL 编码 + /// + /// + /// + public static string UrlEncode(this string str) + { + if (string.IsNullOrEmpty(str)) + { + return ""; + } + + return HttpUtility.UrlEncode(str, Encoding.UTF8); + } + + /// + /// 移除空值项 + /// + /// + public static void RemoveEmptyValueItems(this Dictionary dict) + { + dict.Where(item => string.IsNullOrEmpty(item.Value)).Select(item => item.Key).ToList().ForEach(key => + { + dict.Remove(key); + }); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Extension/EnumExtensions.cs b/src/Znyc.Dispatching.Core/Extension/EnumExtensions.cs new file mode 100644 index 0000000..14d9867 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Extension/EnumExtensions.cs @@ -0,0 +1,317 @@ +using Furion.FriendlyException; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Reflection; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Core +{ + /// + /// 枚举扩展 + /// + public static class EnumExtensions + { + // 枚举显示字典缓存 + private static readonly ConcurrentDictionary> EnumDisplayValueDict = new(); + + // 枚举值字典缓存 + private static readonly ConcurrentDictionary> EnumNameValueDict = new(); + + // 枚举类型缓存 + private static ConcurrentDictionary _enumTypeDict; + + /// + /// 获取枚举对象Key与名称的字典(缓存) + /// + /// + /// + public static Dictionary GetEnumDictionary(Type enumType) + { + if (!enumType.IsEnum) + { + throw Oops.Oh(ErrorCode.D1503); + } + + // 查询缓存 + Dictionary enumDic = EnumNameValueDict.ContainsKey(enumType) + ? EnumNameValueDict[enumType] + : new Dictionary(); + if (enumDic.Count == 0) + { + // 取枚举类型的Key/Value字典集合 + enumDic = GetEnumDictionaryItems(enumType); + + // 缓存 + EnumNameValueDict[enumType] = enumDic; + } + + return enumDic; + } + + /// + /// 获取枚举对象Key与名称的字典 + /// + /// + /// + private static Dictionary GetEnumDictionaryItems(Type enumType) + { + // 获取类型的字段,初始化一个有限长度的字典 + FieldInfo[] enumFields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); + Dictionary enumDic = new(enumFields.Length); + + // 遍历字段数组获取key和name + foreach (FieldInfo enumField in enumFields) + { + int intValue = (int)enumField.GetValue(enumType); + enumDic[intValue] = enumField.Name; + } + + return enumDic; + } + + /// + /// 获取枚举类型key与描述的字典(缓存) + /// + /// + /// + /// + public static Dictionary GetEnumDescDictionary(Type enumType) + { + if (!enumType.IsEnum) + { + throw Oops.Oh(ErrorCode.D1503); + } + + // 查询缓存 + Dictionary enumDic = EnumDisplayValueDict.ContainsKey(enumType) + ? EnumDisplayValueDict[enumType] + : new Dictionary(); + if (enumDic.Count == 0) + { + // 取枚举类型的Key/Value字典集合 + enumDic = GetEnumDescDictionaryItems(enumType); + + // 缓存 + EnumDisplayValueDict[enumType] = enumDic; + } + + return enumDic; + } + + /// + /// 获取枚举类型key与描述的字典(没有描述则获取name) + /// + /// + /// + /// + private static Dictionary GetEnumDescDictionaryItems(Type enumType) + { + // 获取类型的字段,初始化一个有限长度的字典 + FieldInfo[] enumFields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); + Dictionary enumDic = new(enumFields.Length); + + // 遍历字段数组获取key和name + foreach (FieldInfo enumField in enumFields) + { + int intValue = (int)enumField.GetValue(enumType); + DescriptionAttribute desc = enumField.GetDescriptionValue(); + enumDic[intValue] = desc != null && !string.IsNullOrEmpty(desc.Description) + ? desc.Description + : enumField.Name; + } + + return enumDic; + } + + /// + /// 从程序集中查找指定枚举类型 + /// + /// + /// + /// + public static Type TryToGetEnumType(Assembly assembly, string typeName) + { + // 枚举缓存为空则重新加载枚举类型字典 + _enumTypeDict ??= LoadEnumTypeDict(assembly); + + // 按名称查找 + if (_enumTypeDict.ContainsKey(typeName)) + { + return _enumTypeDict[typeName]; + } + + return null; + } + + /// + /// 从程序集中加载所有枚举类型 + /// + /// + /// + private static ConcurrentDictionary LoadEnumTypeDict(Assembly assembly) + { + // 取程序集中所有类型 + Type[] typeArray = assembly.GetTypes(); + + // 过滤非枚举类型,转成字典格式并返回 + Dictionary dict = typeArray.Where(o => o.IsEnum).ToDictionary(o => o.Name, o => o); + ConcurrentDictionary enumTypeDict = new(dict); + return enumTypeDict; + } + + /// + /// 从枚举中获取Description + /// + /// 需要获取枚举描述的枚举 + /// 描述内容 + public static string GetDescription(this Enum enumName) + { + string description = string.Empty; + FieldInfo fieldInfo = enumName.GetType().GetField(enumName.ToString()); + DescriptionAttribute[] attributes = GetDescriptAttr(fieldInfo); + if (attributes != null && attributes.Length > 0) + { + description = attributes[0].Description; + } + else + { + description = enumName.ToString(); + } + + return description; + } + + /// + /// 根据 value 值获取Description + /// + /// + /// + /// + public static string GetDescription(this Type enumType, int value) + { + object Key = GetNameAndValue(enumType).FirstOrDefault(p => p.Value.Equals(value)).Key; + if (Key.IsNull()) + { + return null; + } + + return Key.ToString(); + } + + + /// + /// 根据 value 值获取Description + /// + /// + /// + /// + public static string GetDescriptionByEnumType(Type enumType, int value) + { + object Key = GetNameAndValue(enumType).FirstOrDefault(p => p.Value.Equals(value)).Key; + if (Key.IsNull()) + { + return null; + } + + return Key.ToString(); + } + + + + + /// + /// 获取字段Description + /// + /// FieldInfo + /// DescriptionAttribute[] + private static DescriptionAttribute[] GetDescriptAttr(FieldInfo fieldInfo) + { + if (fieldInfo != null) + { + return (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); + } + + return null; + } + + /// + /// 获取枚举所有名称 + /// + /// 枚举类型typeof(T) + /// 枚举名称列表 + public static List GetEnumNamesList(this Type enumType) + { + return Enum.GetNames(enumType).ToList(); + } + + /// + /// 获取所有枚举对应的值 + /// + /// 枚举类型typeof(T) + /// 枚举值列表 + public static List GetEnumValuesList(this Type enumType) + { + List list = new List(); + foreach (object value in Enum.GetValues(enumType)) + { + list.Add(Convert.ToInt32(value)); + } + + return list; + } + + /// + /// 获取枚举名以及对应的Description + /// + /// 枚举类型typeof(T) + /// 返回Dictionary ,Key为枚举名, Value为枚举对应的Description + public static Dictionary GetNameAndDescriptions(this Type type) + { + if (type.IsEnum) + { + Dictionary dic = new Dictionary(); + Array enumValues = Enum.GetValues(type); + foreach (Enum value in enumValues) + { + dic.Add(value, GetDescription(value)); + } + + return dic; + } + + return null; + } + + /// + /// 获取枚举名以及对应的Value + /// + /// 枚举类型typeof(T) + /// 返回Dictionary ,Key为描述名, Value为枚举对应的值 + public static Dictionary GetNameAndValue(this Type type) + { + if (type.IsEnum) + { + Dictionary dic = new Dictionary(); + Array enumValues = Enum.GetValues(type); + foreach (Enum value in enumValues) + { + dic.Add(GetDescription(value), value.GetHashCode()); + } + + return dic; + } + + return null; + } + + public static string ToDescription(this Enum item) + { + string name = item.ToString(); + DescriptionAttribute desc = item.GetType().GetField(name)?.GetCustomAttribute(); + return desc?.Description ?? name; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Extension/InputBase.cs b/src/Znyc.Dispatching.Core/Extension/InputBase.cs new file mode 100644 index 0000000..24c229e --- /dev/null +++ b/src/Znyc.Dispatching.Core/Extension/InputBase.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Core +{ + /// + /// 通用输入扩展参数(带权限) + /// + public class InputBase : PageInputBase + { + /// + /// 授权菜单 + /// + public List GrantMenuIdList { get; set; } = new(); + + /// + /// 授权角色 + /// + public virtual List GrantRoleIdList { get; set; } = new(); + + /// + /// 授权数据 + /// + public virtual List GrantOrgIdList { get; set; } = new(); + } + + /// + /// 通用分页输入参数 + /// + public class PageInputBase + { + /// + /// 搜索值 + /// + public virtual string SearchValue { get; set; } + + /// + /// 当前页码 + /// + public virtual int PageNo { get; set; } = 1; + + /// + /// 页码容量 + /// + public virtual int PageSize { get; set; } = 20; + + /// + /// 搜索开始时间 + /// + public virtual string SearchBeginTime { get; set; } + + /// + /// 搜索结束时间 + /// + public virtual string SearchEndTime { get; set; } + + /// + /// 排序字段 + /// + public virtual string SortField { get; set; } + + /// + /// 排序方法,默认升序,否则降序(配合antd前端,约定参数为 Ascend,Dscend) + /// + public virtual string SortOrder { get; set; } + + /// + /// 降序排序(不要问我为什么是descend不是desc,前端约定参数就是这样) + /// + public virtual string DescStr { get; set; } = "descend"; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Extension/ObjectExtensions.cs b/src/Znyc.Dispatching.Core/Extension/ObjectExtensions.cs new file mode 100644 index 0000000..72bb73b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Extension/ObjectExtensions.cs @@ -0,0 +1,233 @@ +using System; + +namespace Znyc.Dispatching.Core.Extension +{ + public static class ObjectExtensions + { + /// + /// 判断对象是否为空 + /// + /// + /// + public static bool IsNull(this object obj) + { + return obj == null; + } + + /// + /// 判断对象是否不为空 + /// + /// + /// + public static bool IsNotNull(this object obj) + { + return obj != null; + } + + /// + /// + /// + public static void ThrowIfNull(this object obj) + { + if (obj == null) + { + throw new ArgumentNullException(nameof(obj)); + } + } + + /// + /// + /// + /// + public static int ObjToInt(this object thisValue) + { + int reval = 0; + if (thisValue == null) + { + return 0; + } + + if (thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + + return reval; + } + + /// + /// + /// + /// + /// + public static int ObjToInt(this object thisValue, int errorValue) + { + if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out int reval)) + { + return reval; + } + + return errorValue; + } + + /// + /// + /// + /// + public static double ObjToMoney(this object thisValue) + { + if (thisValue != null && thisValue != DBNull.Value && + double.TryParse(thisValue.ToString(), out double reval)) + { + return reval; + } + + return 0; + } + + /// + /// + /// + /// + /// + public static double ObjToMoney(this object thisValue, double errorValue) + { + if (thisValue != null && thisValue != DBNull.Value && + double.TryParse(thisValue.ToString(), out double reval)) + { + return reval; + } + + return errorValue; + } + + /// + /// + /// + /// + public static string ObjToString(this object thisValue) + { + if (thisValue != null) + { + return thisValue.ToString().Trim(); + } + + return ""; + } + + /// + /// + /// + /// + public static bool IsNotEmptyOrNull(this object thisValue) + { + return ObjToString(thisValue) != "" && ObjToString(thisValue) != "undefined" && + ObjToString(thisValue) != "null"; + } + + /// + /// + /// + /// + /// + public static string ObjToString(this object thisValue, string errorValue) + { + if (thisValue != null) + { + return thisValue.ToString().Trim(); + } + + return errorValue; + } + + /// + /// + /// + /// + public static decimal ObjToDecimal(this object thisValue) + { + if (thisValue != null && thisValue != DBNull.Value && + decimal.TryParse(thisValue.ToString(), out decimal reval)) + { + return reval; + } + + return 0; + } + + /// + /// + /// + /// + /// + public static decimal ObjToDecimal(this object thisValue, decimal errorValue) + { + if (thisValue != null && thisValue != DBNull.Value && + decimal.TryParse(thisValue.ToString(), out decimal reval)) + { + return reval; + } + + return errorValue; + } + + /// + /// + /// + /// + public static DateTime ObjToDate(this object thisValue) + { + DateTime reval = DateTime.MinValue; + if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) + { + reval = Convert.ToDateTime(thisValue); + } + + return reval; + } + + /// + /// + /// + /// + /// + public static DateTime ObjToDate(this object thisValue, DateTime errorValue) + { + DateTime reval = DateTime.MinValue; + if (thisValue != null && thisValue != DBNull.Value && + DateTime.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + + return errorValue; + } + + /// + /// + /// + /// + public static bool ObjToBool(this object thisValue) + { + bool reval = false; + if (thisValue != null && thisValue != DBNull.Value && + bool.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + + return reval; + } + + /// + /// 获取当前时间的时间戳 + /// + /// + /// + public static string DateToTimeStamp(this DateTime thisValue) + { + TimeSpan ts = thisValue - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalSeconds).ToString(); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Extension/PageInputOrder.cs b/src/Znyc.Dispatching.Core/Extension/PageInputOrder.cs new file mode 100644 index 0000000..b96c046 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Extension/PageInputOrder.cs @@ -0,0 +1,28 @@ +namespace Znyc.Dispatching.Core +{ + /// + /// 通用输入帮助类 + /// + public class PageInputOrder + { + /// + /// 排序方式(默认降序) + /// + /// + /// 是否降序 + /// + public static string OrderBuilder(PageInputBase pageInput, bool descSort = true) + { + // 约定默认每张表都有Id排序 + string orderStr = descSort ? "Id Desc" : "Id Asc"; + + // 排序是否可用-排序字段和排序顺序都为非空才启用排序 + if (!string.IsNullOrEmpty(pageInput.SortField) && !string.IsNullOrEmpty(pageInput.SortOrder)) + { + orderStr = $"{pageInput.SortField} {(pageInput.SortOrder == pageInput.DescStr ? "Desc" : "Asc")}"; + } + + return orderStr; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Extension/RestfulResultProvider.cs b/src/Znyc.Dispatching.Core/Extension/RestfulResultProvider.cs new file mode 100644 index 0000000..213f814 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Extension/RestfulResultProvider.cs @@ -0,0 +1,159 @@ +using Furion.DataValidation; +using Furion.DependencyInjection; +using Furion.UnifyResult; +using Furion.UnifyResult.Internal; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Linq; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Core +{ + /// + /// 规范化RESTful风格返回值 + /// + [SuppressSniffer] + [UnifyModel(typeof(XnRestfulResult<>))] + public class RestfulResultProvider : IUnifyResultProvider + { + /// + /// 异常返回值 + /// + /// + /// + /// + public IActionResult OnException(ExceptionContext context, ExceptionMetadata metadata) + { + return new JsonResult(new XnRestfulResult + { + Code = metadata.StatusCode, + Success = false, + Data = null, + Message = metadata.Errors, + Extras = UnifyContext.Take(), + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + }); + } + + /// + /// 成功返回值 + /// + /// + /// + /// + public IActionResult OnSucceeded(ActionExecutedContext context, object data) + { + return new JsonResult(new XnRestfulResult + { + Code = context.Result is EmptyResult + ? StatusCodes.Status204NoContent + : StatusCodes.Status200OK, // 处理没有返回值情况 204 + Success = true, + Data = data, + Message = "", + Extras = UnifyContext.Take(), + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + }); + } + + /// + /// 验证失败返回值 + /// + /// + /// + /// + public IActionResult OnValidateFailed(ActionExecutingContext context, ValidationMetadata metadata) + { + return new JsonResult(new XnRestfulResult + { + Code = StatusCodes.Status400BadRequest, + Success = false, + Data = null, + Message = metadata.ValidationResult.First().Value[0], + Extras = UnifyContext.Take(), + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + }); + } + + /// + /// 处理输出状态码 + /// + /// + /// + /// + /// + public async Task OnResponseStatusCodes(HttpContext context, int statusCode, UnifyResultSettingsOptions options) + { + // 设置响应状态码 + UnifyContext.SetResponseStatusCodes(context, statusCode, options); + + switch (statusCode) + { + // 处理 401 状态码 + case StatusCodes.Status401Unauthorized: + await context.Response.WriteAsJsonAsync(new XnRestfulResult + { + Code = StatusCodes.Status401Unauthorized, + Success = false, + Data = null, + Message = "401 未经授权", + Extras = UnifyContext.Take(), + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + }); + break; + // 处理 403 状态码 + case StatusCodes.Status403Forbidden: + await context.Response.WriteAsJsonAsync(new XnRestfulResult + { + Code = StatusCodes.Status403Forbidden, + Success = false, + Data = null, + Message = "403 禁止访问", + Extras = UnifyContext.Take(), + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + }); + break; + } + } + } + + /// + /// RESTful风格---XIAONUO返回格式 + /// + /// + [SuppressSniffer] + public class XnRestfulResult + { + /// + /// 执行成功 + /// + public bool Success { get; set; } + + /// + /// 状态码 + /// + public int? Code { get; set; } + + /// + /// 错误信息 + /// + public object Message { get; set; } + + /// + /// 数据 + /// + public T Data { get; set; } + + /// + /// 附加数据 + /// + public object Extras { get; set; } + + /// + /// 时间戳 + /// + public long Timestamp { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Extension/ReturnPageResult.cs b/src/Znyc.Dispatching.Core/Extension/ReturnPageResult.cs new file mode 100644 index 0000000..a025562 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Extension/ReturnPageResult.cs @@ -0,0 +1,45 @@ +using Mapster; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Core +{ + public class PageResult + { + public int PageNo { get; set; } + public int PageSize { get; set; } + public int TotalPage { get; set; } + public int TotalRows { get; set; } + public ICollection Rows { get; set; } + } + + /// + /// 分页列表结果 + /// + /// + public class ReturnPageResult where T : new() + { + public static dynamic PageResult(PagedList page) + { + return new + { + PageNo = page.PageIndex, + page.PageSize, + TotalPage = page.TotalPages, + TotalRows = page.TotalCount, + Rows = page.Items //.Adapt>(), + }; + } + + public static PageResult PageResult(PagedList page) + { + return new() + { + PageNo = page.PageIndex, + PageSize = page.PageSize, + TotalPage = page.TotalPages, + TotalRows = page.TotalCount, + Rows = page.Items.Adapt>() + }; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Extension/StringExtensions.cs b/src/Znyc.Dispatching.Core/Extension/StringExtensions.cs new file mode 100644 index 0000000..1f6f32b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Extension/StringExtensions.cs @@ -0,0 +1,110 @@ +using System; +using System.Linq; +using System.Text; +using Znyc.Dispatching.Core.Helpers; + +namespace Znyc.Dispatching.Core.Extension +{ + public static class StringExtensions + { + /// + /// 判断字符串是否为Null、空 + /// + /// + /// + public static bool IsNull(this string s) + { + return string.IsNullOrWhiteSpace(s); + } + + /// + /// 判断字符串是否不为Null、空 + /// + /// + /// + public static bool NotNull(this string s) + { + return !string.IsNullOrWhiteSpace(s); + } + + /// + /// 与字符串进行比较,忽略大小写 + /// + /// + /// + /// + public static bool EqualsIgnoreCase(this string s, string value) + { + return s.Equals(value, StringComparison.OrdinalIgnoreCase); + } + + /// + /// 首字母转小写 + /// + /// + /// + public static string FirstCharToLower(this string s) + { + if (string.IsNullOrEmpty(s)) + { + return s; + } + + string str = s.First().ToString().ToLower() + s.Substring(1); + return str; + } + + /// + /// 首字母转大写 + /// + /// + /// + public static string FirstCharToUpper(this string s) + { + if (string.IsNullOrEmpty(s)) + { + return s; + } + + string str = s.First().ToString().ToUpper() + s.Substring(1); + return str; + } + + /// + /// 转为Base64,UTF-8格式 + /// + /// + /// + public static string ToBase64(this string s) + { + return s.ToBase64(Encoding.UTF8); + } + + /// + /// 转为Base64 + /// + /// + /// 编码 + /// + public static string ToBase64(this string s, Encoding encoding) + { + if (s.IsNull()) + { + return string.Empty; + } + + byte[] bytes = encoding.GetBytes(s); + return bytes.ToBase64(); + } + + public static string ToPath(this string s) + { + if (s.IsNull()) + { + return string.Empty; + } + + return s.Replace(@"\", "/"); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Files/FileInfo.cs b/src/Znyc.Dispatching.Core/Files/FileInfo.cs new file mode 100644 index 0000000..8f407cf --- /dev/null +++ b/src/Znyc.Dispatching.Core/Files/FileInfo.cs @@ -0,0 +1,82 @@ +using System.IO; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Core +{ + /// + /// 文件信息 + /// + public class FileInfo + { + public FileInfo() + { + } + + /// + /// 初始化文件信息 + /// + /// 文件名称 + /// 大小 + public FileInfo(string fileName, long size = 0L) + { + FileName = fileName; + Size = new FileSize(size); + Extension = Path.GetExtension(FileName)?.TrimStart('.'); + } + + /// + /// 上传路径 + /// + public string UploadPath { get; set; } + + /// + /// 请求路径 + /// + public string RequestPath { get; set; } + + /// + /// 相对路径 + /// + public string RelativePath { get; set; } + + /// + /// 文件名 + /// + public string FileName { get; set; } + + /// + /// 保存名 + /// + public string SaveName { get; set; } + + /// + /// 文件大小 + /// + public FileSize Size { get; set; } + + /// + /// 扩展名 + /// + public string Extension { get; set; } + + /// + /// 文件目录 + /// + public string FileDirectory => Path.Combine(UploadPath, RelativePath).ToPath(); + + /// + /// 文件请求路径 + /// + public string FileRequestPath => Path.Combine(RequestPath, RelativePath, SaveName).ToPath(); + + /// + /// 文件相对路径 + /// + public string FileRelativePath => Path.Combine(RelativePath, SaveName).ToPath(); + + /// + /// 文件路径 + /// + public string FilePath => Path.Combine(UploadPath, RelativePath, SaveName).ToPath(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Files/FileSize.cs b/src/Znyc.Dispatching.Core/Files/FileSize.cs new file mode 100644 index 0000000..a0ae9f7 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Files/FileSize.cs @@ -0,0 +1,97 @@ +using Znyc.Dispatching.Core.Helpers; + +namespace Znyc.Dispatching.Core +{ + /// + /// 文件大小 + /// + public struct FileSize + { + /// + /// 初始化文件大小 + /// + /// 文件大小 + /// 文件大小单位 + public FileSize(long size, FileSizeUnit unit = FileSizeUnit.Byte) + { + switch (unit) + { + case FileSizeUnit.K: + Size = size * 1024; + break; + + case FileSizeUnit.M: + Size = size * 1024 * 1024; + break; + + case FileSizeUnit.G: + Size = size * 1024 * 1024 * 1024; + break; + + default: + Size = size; + break; + } + } + + /// + /// 文件字节长度 + /// + public long Size { get; } + + /// + /// 获取文件大小,单位:字节 + /// + public long GetSize() + { + return Size; + } + + /// + /// 获取文件大小,单位:K + /// + public double GetSizeByK() + { + return (Size / 1024.0).ToDouble(2); + } + + /// + /// 获取文件大小,单位:M + /// + public double GetSizeByM() + { + return (Size / 1024.0 / 1024.0).ToDouble(2); + } + + /// + /// 获取文件大小,单位:G + /// + public double GetSizeByG() + { + return (Size / 1024.0 / 1024.0 / 1024.0).ToDouble(2); + } + + /// + /// 输出描述 + /// + public override string ToString() + { + if (Size >= 1024 * 1024 * 1024) + { + return $"{GetSizeByG()} {FileSizeUnit.G.ToDescription()}"; + } + + if (Size >= 1024 * 1024) + { + return $"{GetSizeByM()} {FileSizeUnit.M.ToDescription()}"; + } + + if (Size >= 1024) + { + return $"{GetSizeByK()} {FileSizeUnit.K.ToDescription()}"; + } + + return $"{Size} {FileSizeUnit.Byte.ToDescription()}"; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Files/FileSizeUnit.cs b/src/Znyc.Dispatching.Core/Files/FileSizeUnit.cs new file mode 100644 index 0000000..60628d9 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Files/FileSizeUnit.cs @@ -0,0 +1,30 @@ +using System.ComponentModel; + +namespace Znyc.Dispatching.Core +{ + /// + /// 文件大小单位 + /// + public enum FileSizeUnit + { + /// + /// 字节 + /// + [Description("B")] Byte, + + /// + /// K字节 + /// + [Description("KB")] K, + + /// + /// M字节 + /// + [Description("MB")] M, + + /// + /// G字节 + /// + [Description("GB")] G + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Filter/LogExceptionHandler.cs b/src/Znyc.Dispatching.Core/Filter/LogExceptionHandler.cs new file mode 100644 index 0000000..d1ea1e5 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Filter/LogExceptionHandler.cs @@ -0,0 +1,56 @@ +using Furion; +using Furion.DependencyInjection; +using Furion.FriendlyException; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Security.Claims; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Core +{ + /// + /// 全局异常处理 + /// + public class LogExceptionHandler : IGlobalExceptionHandler, ISingleton + { + private readonly ILogger _logger; + + public LogExceptionHandler(ILogger logger) + { + _logger = logger; + } + + public Task OnExceptionAsync(ExceptionContext context) + { + ClaimsPrincipal userContext = App.User; + try + { + var logEX = new LogEx + { + Account = userContext?.FindFirstValue(ClaimConst.CLAINM_ACCOUNT), + Name = userContext?.FindFirstValue(ClaimConst.CLAINM_USERNAME), + ClassName = context.Exception.TargetSite.DeclaringType?.FullName, + MethodName = context.Exception.TargetSite.Name, + ExceptionName = context.Exception.Message, + ExceptionMsg = context.Exception.Message, + ExceptionSource = context.Exception.Source, + StackTrace = context.Exception.StackTrace, + ParamsObj = context.Exception.TargetSite.GetParameters().ToString(), + ExceptionTime = DateTime.Now + }; + _logger.LogError(JsonConvert.SerializeObject(logEX)); + Console.WriteLine($"logEX:{JsonConvert.SerializeObject(logEX)}"); + Console.WriteLine($"InnerException:{context.Exception.InnerException}"); + } + catch (Exception ex) + { + _logger.LogError("LogError", ex.Message); + + } + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Filter/RequestActionFilter.cs b/src/Znyc.Dispatching.Core/Filter/RequestActionFilter.cs new file mode 100644 index 0000000..5a80d08 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Filter/RequestActionFilter.cs @@ -0,0 +1,79 @@ +using Furion; +using Furion.JsonSerialization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Diagnostics; +using System.Security.Claims; +using System.Threading.Tasks; +using UAParser; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.SimpleQueue; + +namespace Znyc.Dispatching.Core +{ + /// + /// 请求日志拦截 + /// + public class RequestActionFilter : IAsyncActionFilter + { + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + HttpContext httpContext = context.HttpContext; + HttpRequest httpRequest = httpContext.Request; + + Stopwatch sw = new Stopwatch(); + sw.Start(); + ActionExecutedContext actionContext = await next(); + sw.Stop(); + + // 判断是否请求成功(没有异常就是请求成功) + bool isRequestSucceed = actionContext.Exception == null; + IHeaderDictionary headers = httpRequest.Headers; + ClientInfo clientInfo = headers.ContainsKey("User-Agent") + ? Parser.GetDefault().Parse(headers["User-Agent"]) + : null; + ControllerActionDescriptor actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; + + // 日志写入简单队列 + IConcurrentQueue _logOpQueue = App.GetService>(); + _logOpQueue.Add(new LogOp + { + Name = httpContext.User?.FindFirstValue(ClaimConst.CLAINM_USERNAME), + Success = isRequestSucceed ? YesOrNotEnum.Y : YesOrNotEnum.N, + Ip = httpContext.GetRemoteIpAddressToIPv4(), + Location = httpRequest.GetRequestUrlAddress(), + Browser = clientInfo?.UA.Family + clientInfo?.UA.Major, + Os = clientInfo?.OS.Family + clientInfo?.OS.Major, + Url = httpRequest.Path, + ClassName = context.Controller.ToString(), + MethodName = actionDescriptor.ActionName, + ReqMethod = httpRequest.Method, + Param = JSON.Serialize(context.ActionArguments.Count < 1 ? "" : context.ActionArguments), + //Result = JSON.Serialize(actionContext.Result), // 序列化异常,比如验证码 + ElapsedTime = sw.ElapsedMilliseconds, + OpTime = DateTime.Now, + Account = httpContext.User?.FindFirstValue(ClaimConst.CLAINM_ACCOUNT) + }); + + //MessageCenter.Send("create:oplog", new LogOp + //{ + // Name = httpContext.User?.FindFirstValue(ClaimConst.CLAINM_USERNAME), + // Success = isRequestSucceed ? YesOrNot.Y : YesOrNot.N, + // Ip = httpContext.GetRemoteIpAddressToIPv4(), + // Location = httpRequest.GetRequestUrlAddress(), + // Browser = clientInfo?.UA.Family + clientInfo?.UA.Major, + // Os = clientInfo?.OS.Family + clientInfo?.OS.Major, + // Url = httpRequest.Path, + // ClassName = context.Controller.ToString(), + // MethodName = actionDescriptor?.ActionName, + // ReqMethod = httpRequest.Method, + // Param = JSON.Serialize(context.ActionArguments.Count < 1 ? "" : context.ActionArguments), + // ElapsedTime = sw.ElapsedMilliseconds, + // OpTime = DateTime.Now, + // Account = httpContext.User?.FindFirstValue(ClaimConst.CLAINM_ACCOUNT) + //}); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Filter/XSSFilterAttribute.cs b/src/Znyc.Dispatching.Core/Filter/XSSFilterAttribute.cs new file mode 100644 index 0000000..c50f60e --- /dev/null +++ b/src/Znyc.Dispatching.Core/Filter/XSSFilterAttribute.cs @@ -0,0 +1,85 @@ +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using Znyc.Dispatching.Core.Helpers; + +namespace Znyc.Dispatching.Core.Filter +{ + public class FieldFilterAttribute : Attribute, IActionFilter + { + private XSSHelper _xSSHelper; + public FieldFilterAttribute() + { + _xSSHelper = new XSSHelper(); + } + + //在Action方法之回之后调用 + public void OnActionExecuted(ActionExecutedContext context) + { + + } + + //在调用Action方法之前调用 + public void OnActionExecuting(ActionExecutingContext context) + { + //获取Action参数集合 + var ps = context.ActionDescriptor.Parameters; + //遍历参数集合 + foreach (var p in ps) + { + if (context.ActionArguments[p.Name] != null) + { + //当参数等于字符串 + if (p.ParameterType.Equals(typeof(string))) + { + context.ActionArguments[p.Name] = _xSSHelper.Filter(context.ActionArguments[p.Name].ToString()); + } + else if (p.ParameterType.IsClass)//当参数等于类 + { + ModelFieldFilter(p.Name, p.ParameterType, context.ActionArguments[p.Name]); + } + } + + } + } + + /// + /// 遍历修改类的字符串属性 + /// + /// 类名 + /// 数据类型 + /// 对象 + /// + private object ModelFieldFilter(string key, Type t, object obj) + { + //获取类的属性集合 + //var ats = t.GetCustomAttributes(typeof(FieldFilterAttribute), false); + + + if (obj != null) + { + //获取类的属性集合 + var pps = t.GetProperties(); + + foreach (var pp in pps) + { + if (pp.GetValue(obj) != null) + { + //当属性等于字符串 + if (pp.PropertyType.Equals(typeof(string))) + { + string value = pp.GetValue(obj).ToString(); + pp.SetValue(obj, _xSSHelper.Filter(value)); + } + else if (pp.PropertyType.IsClass)//当属性等于类进行递归 + { + pp.SetValue(obj, ModelFieldFilter(pp.Name, pp.PropertyType, pp.GetValue(obj))); + } + } + + } + } + + return obj; + } + } +} diff --git a/src/Znyc.Dispatching.Core/Helpers/ByteConvertHelper.cs b/src/Znyc.Dispatching.Core/Helpers/ByteConvertHelper.cs new file mode 100644 index 0000000..5a23dc8 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/ByteConvertHelper.cs @@ -0,0 +1,45 @@ +using Newtonsoft.Json; +using System.Text; + +namespace Znyc.Dispatching.Core.Helpers +{ + /// + /// byte转换类 + /// + public class ByteConvertHelper + { + /// + /// 将对象转换为byte数组 + /// + /// 被转换对象 + /// 转换后byte数组 + public static byte[] Object2Bytes(object obj) + { + string json = JsonConvert.SerializeObject(obj); + byte[] serializedResult = Encoding.UTF8.GetBytes(json); + return serializedResult; + } + + /// + /// 将byte数组转换成对象 + /// + /// 被转换byte数组 + /// 转换完成后的对象 + public static object Bytes2Object(byte[] buff) + { + string json = Encoding.UTF8.GetString(buff); + return JsonConvert.DeserializeObject(json); + } + + /// + /// 将byte数组转换成对象 + /// + /// 被转换byte数组 + /// 转换完成后的对象 + public static T Bytes2Object(byte[] buff) + { + string json = Encoding.UTF8.GetString(buff); + return JsonConvert.DeserializeObject(json); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/ConvertGps.cs b/src/Znyc.Dispatching.Core/Helpers/ConvertGps.cs new file mode 100644 index 0000000..7da30ef --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/ConvertGps.cs @@ -0,0 +1,154 @@ +using System; +using Znyc.Dispatching.Core.MapModel; + +namespace Znyc.Dispatching.Core.Helpers +{ + public class ConvertGps + { + private static readonly double pi = 3.1415926535897932384626; + private static readonly double a = 6378245.0; + private static readonly double ee = 0.00669342162296594323; + private static readonly double bd_pi = 3.14159265358979324 * 3000.0 / 180.0; + + public static bool OutOfChina(double lat, double lon) + { + if (lon < 72.004 || lon > 137.8347) + { + return true; + } + + if (lat < 0.8293 || lat > 55.8271) + { + return true; + } + + return false; + } + + private static double TransformLat(double x, double y) + { + double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + + 0.2 * Math.Sqrt(Math.Abs(x)); + ret += (20.0 * Math.Sin(6.0 * x * pi) + 20.0 * Math.Sin(2.0 * x * pi)) * 2.0 / 3.0; + ret += (20.0 * Math.Sin(y * pi) + 40.0 * Math.Sin(y / 3.0 * pi)) * 2.0 / 3.0; + ret += (160.0 * Math.Sin(y / 12.0 * pi) + 320 * Math.Sin(y * pi / 30.0)) * 2.0 / 3.0; + return ret; + } + + private static double TransformLon(double x, double y) + { + double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 + * Math.Sqrt(Math.Abs(x)); + ret += (20.0 * Math.Sin(6.0 * x * pi) + 20.0 * Math.Sin(2.0 * x * pi)) * 2.0 / 3.0; + ret += (20.0 * Math.Sin(x * pi) + 40.0 * Math.Sin(x / 3.0 * pi)) * 2.0 / 3.0; + ret += (150.0 * Math.Sin(x / 12.0 * pi) + 300.0 * Math.Sin(x / 30.0 + * pi)) * 2.0 / 3.0; + return ret; + } + + // 【84】-->【GCJ-02】 + public static PointLatLng Gps84ToGcj02(PointLatLng gpoint) + { + if (OutOfChina(gpoint.Lat, gpoint.Lng)) + { + return new PointLatLng(0, 0); + } + + double dLat = TransformLat(gpoint.Lng - 105.0, gpoint.Lat - 35.0); + double dLon = TransformLon(gpoint.Lng - 105.0, gpoint.Lat - 35.0); + double radLat = gpoint.Lat / 180.0 * pi; + double magic = Math.Sin(radLat); + magic = 1 - ee * magic * magic; + double sqrtMagic = Math.Sqrt(magic); + dLat = dLat * 180.0 / (a * (1 - ee) / (magic * sqrtMagic) * pi); + dLon = dLon * 180.0 / (a / sqrtMagic * Math.Cos(radLat) * pi); + double mgLat = gpoint.Lat + dLat; + double mgLon = gpoint.Lng + dLon; + return new PointLatLng(mgLat, mgLon); + } + + // 【GCJ-02】-->【84】 + public static PointLatLng Gcj02ToGps84(PointLatLng gpoint) + { + PointLatLng gps = Transform(gpoint); + double lontitude = gpoint.Lng * 2 - gps.Lng; + double latitude = gpoint.Lat * 2 - gps.Lat; + return new PointLatLng(latitude, lontitude); + } + + // 【GCJ-02】-->【BD-09】 + public static PointLatLng Gcj02ToBd09(PointLatLng gpoint) + { + double x = gpoint.Lng, y = gpoint.Lat; + double z = Math.Sqrt(x * x + y * y) + 0.00002 * Math.Sin(y * bd_pi); + double theta = Math.Atan2(y, x) + 0.000003 * Math.Cos(x * bd_pi); + double bd_lon = z * Math.Cos(theta) + 0.0065; + double bd_lat = z * Math.Sin(theta) + 0.006; + double resLng = Retain6(bd_lon); + double resLat = Retain6(bd_lat); + return new PointLatLng(resLat, resLng); + } + + // 【BD-09】-->【GCJ-02】 + public static PointLatLng Bd09ToGcj02(PointLatLng bdPoint) + { + double x = bdPoint.Lng - 0.0065, y = bdPoint.Lat - 0.006; + double z = Math.Sqrt(x * x + y * y) - 0.00002 * Math.Sin(y * bd_pi); + double theta = Math.Atan2(y, x) - 0.000003 * Math.Cos(x * bd_pi); + double gg_lon = z * Math.Cos(theta); + double gg_lat = z * Math.Sin(theta); + double resLng = Retain6(gg_lon); + double resLat = Retain6(gg_lat); + return new PointLatLng(resLat, resLng); + } + + // 【BD-09】-->【84】 + public static PointLatLng Bd09ToGps84(PointLatLng bdPoint) + { + PointLatLng gcj02 = Bd09ToGcj02(bdPoint); + PointLatLng map84 = Gcj02ToGps84(gcj02); + //保留小数点后六位 + //map84.Lat = Retain6(map84.Lat); + //map84.Lng = Retain6(map84.Lng); + return map84; + } + + //【84】-->【BD-09】 + public static PointLatLng Gps84ToBd09(PointLatLng gpsPoint) + { + PointLatLng gcj02 = Gps84ToGcj02(gpsPoint); + PointLatLng bd09 = Gcj02ToBd09(gcj02); + return bd09; + } + + private static PointLatLng Transform(PointLatLng gpoint) + { + if (OutOfChina(gpoint.Lat, gpoint.Lng)) + { + return new PointLatLng(gpoint.Lat, gpoint.Lng); + } + + double dLat = TransformLat(gpoint.Lng - 105.0, gpoint.Lat - 35.0); + double dLon = TransformLon(gpoint.Lng - 105.0, gpoint.Lat - 35.0); + double radLat = gpoint.Lat / 180.0 * pi; + double magic = Math.Sin(radLat); + magic = 1 - ee * magic * magic; + double sqrtMagic = Math.Sqrt(magic); + dLat = dLat * 180.0 / (a * (1 - ee) / (magic * sqrtMagic) * pi); + dLon = dLon * 180.0 / (a / sqrtMagic * Math.Cos(radLat) * pi); + double mgLat = gpoint.Lat + dLat; + double mgLon = gpoint.Lng + dLon; + return new PointLatLng(mgLat, mgLon); + } + + /// + /// 保留小数点后六位 + /// + /// + /// + private static double Retain6(double num) + { + return Math.Round(num, 6); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/ConvertHelper.cs b/src/Znyc.Dispatching.Core/Helpers/ConvertHelper.cs new file mode 100644 index 0000000..e1d4cfd --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/ConvertHelper.cs @@ -0,0 +1,868 @@ +using System; +using System.Text; +using System.Threading; + +namespace Znyc.Dispatching.Core.Helpers +{ + /// + /// 处理数据类型转换,数制转换、编码转换相关的类 + /// + public sealed class ConvertHelper + { + #region 将byte[]转换成int + + /// + /// 将byte[]转换成int + /// + /// 需要转换成整数的byte数组 + public static int BytesToInt32(byte[] data) + { + //如果传入的字节数组长度小于4,则返回0 + if (data.Length < 4) + { + return 0; + } + + //定义要返回的整数 + int num = 0; + + //如果传入的字节数组长度大于4,需要进行处理 + if (data.Length >= 4) + { + //创建一个临时缓冲区 + byte[] tempBuffer = new byte[4]; + + //将传入的字节数组的前4个字节复制到临时缓冲区 + Buffer.BlockCopy(data, 0, tempBuffer, 0, 4); + + //将临时缓冲区的值转换成整数,并赋给num + num = BitConverter.ToInt32(tempBuffer, 0); + } + + //返回整数 + return num; + } + + #endregion 将byte[]转换成int + + #region 各进制数间转换 + + /// + /// 实现各进制数间的转换。ConvertBase("15",10,16)表示将十进制数15转换为16进制的数。 + /// + /// 要转换的值,即原值 + /// 原值的进制,只能是2,8,10,16四个值。 + /// 要转换到的目标进制,只能是2,8,10,16四个值。 + public static string ConvertBase(string value, int from, int to) + { + if (!isBaseNumber(from)) + { + throw new ArgumentException("参数from只能是2,8,10,16四个值。"); + } + + if (!isBaseNumber(to)) + { + throw new ArgumentException("参数to只能是2,8,10,16四个值。"); + } + + int intValue = Convert.ToInt32(value, from); //先转成10进制 + string result = Convert.ToString(intValue, to); //再转成目标进制 + if (to == 2) + { + int resultLength = result.Length; //获取二进制的长度 + switch (resultLength) + { + case 7: + result = "0" + result; + break; + + case 6: + result = "00" + result; + break; + + case 5: + result = "000" + result; + break; + + case 4: + result = "0000" + result; + break; + + case 3: + result = "00000" + result; + break; + } + } + + return result; + } + + /// + /// 判断是否是 2 8 10 16 + /// + /// + /// + private static bool isBaseNumber(int baseNumber) + { + if (baseNumber == 2 || baseNumber == 8 || baseNumber == 10 || baseNumber == 16) + { + return true; + } + + return false; + } + + #endregion 各进制数间转换 + + #region 使用指定字符集将string转换成byte[] + + /// + /// 将string转换成byte[] + /// + /// 要转换的字符串 + public static byte[] StringToBytes(string text) + { + return Encoding.Default.GetBytes(text); + } + + /// + /// 使用指定字符集将string转换成byte[] + /// + /// 要转换的字符串 + /// 字符编码 + public static byte[] StringToBytes(string text, Encoding encoding) + { + return encoding.GetBytes(text); + } + + #endregion 使用指定字符集将string转换成byte[] + + #region 使用指定字符集将byte[]转换成string + + /// + /// 将byte[]转换成string + /// + /// 要转换的字节数组 + public static string BytesToString(byte[] bytes) + { + return Encoding.Default.GetString(bytes); + } + + /// + /// 使用指定字符集将byte[]转换成string + /// + /// 要转换的字节数组 + /// 字符编码 + public static string BytesToString(byte[] bytes, Encoding encoding) + { + return encoding.GetString(bytes); + } + + #endregion 使用指定字符集将byte[]转换成string + + #region 将数据转换为整型 + + /// + /// 将数据转换为整型 转换失败返回默认值 + /// + /// 数据类型 + /// 数据 + /// 默认值 + /// + public static int ToInt32(T data, int defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToInt32(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为整型 转换失败返回默认值 + /// + /// 数据 + /// 默认值 + /// + public static int ToInt32(string data, int defValue) + { + //如果为空则返回默认值 + if (string.IsNullOrEmpty(data)) + { + return defValue; + } + + if (int.TryParse(data, out int temp)) + { + return temp; + } + + return defValue; + } + + /// + /// 将数据转换为整型 转换失败返回默认值 + /// + /// 数据 + /// 默认值 + /// + public static int ToInt32(object data, int defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToInt32(data); + } + catch + { + return defValue; + } + } + + #endregion 将数据转换为整型 + + #region 将数据转换为布尔型 + + /// + /// 将数据转换为布尔类型 转换失败返回默认值 + /// + /// 数据类型 + /// 数据 + /// 默认值 + /// + public static bool ToBoolean(T data, bool defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToBoolean(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为布尔类型 转换失败返回 默认值 + /// + /// 数据 + /// 默认值 + /// + public static bool ToBoolean(string data, bool defValue) + { + //如果为空则返回默认值 + if (string.IsNullOrEmpty(data)) + { + return defValue; + } + + if (bool.TryParse(data, out bool temp)) + { + return temp; + } + + return defValue; + } + + /// + /// 将数据转换为布尔类型 转换失败返回 默认值 + /// + /// 数据 + /// 默认值 + /// + public static bool ToBoolean(object data, bool defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToBoolean(data); + } + catch + { + return defValue; + } + } + + #endregion 将数据转换为布尔型 + + #region 将数据转换为单精度浮点型 + + /// + /// 将数据转换为单精度浮点型 转换失败 返回默认值 + /// + /// 数据类型 + /// 数据 + /// 默认值 + /// + public static float ToFloat(T data, float defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToSingle(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为单精度浮点型 转换失败返回默认值 + /// + /// 数据 + /// 默认值 + /// + public static float ToFloat(object data, float defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToSingle(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为单精度浮点型 转换失败返回默认值 + /// + /// 数据 + /// 默认值 + /// + public static float ToFloat(string data, float defValue) + { + //如果为空则返回默认值 + if (string.IsNullOrEmpty(data)) + { + return defValue; + } + + if (float.TryParse(data, out float temp)) + { + return temp; + } + + return defValue; + } + + #endregion 将数据转换为单精度浮点型 + + #region 将数据转换为双精度浮点型 + + /// + /// 将数据转换为双精度浮点型 转换失败返回默认值 + /// + /// 数据的类型 + /// 要转换的数据 + /// 默认值 + /// + public static double ToDouble(T data, double defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToDouble(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为双精度浮点型,并设置小数位 转换失败返回默认值 + /// + /// 数据的类型 + /// 要转换的数据 + /// 小数的位数 + /// 默认值 + /// + public static double ToDouble(T data, int decimals, double defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Math.Round(Convert.ToDouble(data), decimals); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为双精度浮点型 转换失败返回默认值 + /// + /// 要转换的数据 + /// 默认值 + /// + public static double ToDouble(object data, double defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToDouble(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为双精度浮点型 转换失败返回默认值 + /// + /// 要转换的数据 + /// 默认值 + /// + public static double ToDouble(string data, double defValue) + { + //如果为空则返回默认值 + if (string.IsNullOrEmpty(data)) + { + return defValue; + } + + if (double.TryParse(data, out double temp)) + { + return temp; + } + + return defValue; + } + + /// + /// 将数据转换为双精度浮点型,并设置小数位 转换失败返回默认值 + /// + /// 要转换的数据 + /// 小数的位数 + /// 默认值 + /// + public static double ToDouble(object data, int decimals, double defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Math.Round(Convert.ToDouble(data), decimals); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为双精度浮点型,并设置小数位 转换失败返回默认值 + /// + /// 要转换的数据 + /// 小数的位数 + /// 默认值 + /// + public static double ToDouble(string data, int decimals, double defValue) + { + //如果为空则返回默认值 + if (string.IsNullOrEmpty(data)) + { + return defValue; + } + + if (double.TryParse(data, out double temp)) + { + return Math.Round(temp, decimals); + } + + return defValue; + } + + #endregion 将数据转换为双精度浮点型 + + #region 将数据转换为指定类型 + + /// + /// 将数据转换为指定类型 + /// + /// 转换的数据 + /// 转换的目标类型 + public static object ConvertTo(object data, Type targetType) + { + if (data == null || Convert.IsDBNull(data)) + { + return null; + } + + Type type2 = data.GetType(); + if (targetType == type2) + { + return data; + } + + if ((targetType == typeof(Guid) || targetType == typeof(Guid?)) && type2 == typeof(string)) + { + if (string.IsNullOrEmpty(data.ToString())) + { + return null; + } + + return new Guid(data.ToString()); + } + + if (targetType.IsEnum) + { + try + { + return Enum.Parse(targetType, data.ToString(), true); + } + catch + { + return Enum.ToObject(targetType, data); + } + } + + if (targetType.IsGenericType) + { + targetType = targetType.GetGenericArguments()[0]; + } + + return Convert.ChangeType(data, targetType); + } + + /// + /// 将数据转换为指定类型 + /// + /// 转换的目标类型 + /// 转换的数据 + public static T ConvertTo(object data) + { + if (data == null || Convert.IsDBNull(data)) + { + return default; + } + + object obj = ConvertTo(data, typeof(T)); + if (obj == null) + { + return default; + } + + return (T)obj; + } + + #endregion 将数据转换为指定类型 + + #region = ChangeType = + + /// + /// + /// + /// + /// + public static object ChangeType(object obj, Type conversionType) + { + return ChangeType(obj, conversionType, Thread.CurrentThread.CurrentCulture); + } + + /// + /// + /// + /// + /// + /// + public static object ChangeType(object obj, Type conversionType, IFormatProvider provider) + { + #region Nullable + + Type nullableType = Nullable.GetUnderlyingType(conversionType); + if (nullableType != null) + { + if (obj == null) + { + return null; + } + + return Convert.ChangeType(obj, nullableType, provider); + } + + #endregion Nullable + + if (typeof(Enum).IsAssignableFrom(conversionType)) + { + return Enum.Parse(conversionType, obj.ToString()); + } + + return Convert.ChangeType(obj, conversionType, provider); + } + + #endregion = ChangeType = + + #region 将数据转换Decimal + + /// + /// 将数据转换为Decimal 转换失败返回默认值 + /// + /// 数据类型 + /// 数据 + /// 默认值 + /// + public static decimal ToDecimal(T data, decimal defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToDecimal(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为Decimal 转换失败返回 默认值 + /// + /// 数据 + /// 默认值 + /// + public static decimal ToDecimal(object data, decimal defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToDecimal(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为Decimal 转换失败返回 默认值 + /// + /// 数据 + /// 默认值 + /// + public static decimal ToDecimal(string data, decimal defValue) + { + //如果为空则返回默认值 + if (string.IsNullOrEmpty(data)) + { + return defValue; + } + + if (decimal.TryParse(data, out decimal temp)) + { + return temp; + } + + return defValue; + } + + #endregion 将数据转换Decimal + + #region 将数据转换为DateTime + + /// + /// 将数据转换为DateTime 转换失败返回默认值 + /// + /// 数据类型 + /// 数据 + /// 默认值 + /// + public static DateTime ToDateTime(T data, DateTime defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToDateTime(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为DateTime 转换失败返回 默认值 + /// + /// 数据 + /// 默认值 + /// + public static DateTime ToDateTime(object data, DateTime defValue) + { + //如果为空则返回默认值 + if (data == null || Convert.IsDBNull(data)) + { + return defValue; + } + + try + { + return Convert.ToDateTime(data); + } + catch + { + return defValue; + } + } + + /// + /// 将数据转换为DateTime 转换失败返回 默认值 + /// + /// 数据 + /// 默认值 + /// + public static DateTime ToDateTime(string data, DateTime defValue) + { + //如果为空则返回默认值 + if (string.IsNullOrEmpty(data)) + { + return defValue; + } + + DateTime temp = DateTime.Now; + + if (DateTime.TryParse(data, out temp)) + { + return temp; + } + + return defValue; + } + + #endregion 将数据转换为DateTime + + #region 半角全角转换 + + /// + /// 转全角的函数(SBC case) + /// + /// 任意字符串 + /// 全角字符串 + /// + /// 全角空格为12288,半角空格为32 + /// 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 + /// + public static string ConvertToSBC(string input) + { + //半角转全角: + char[] c = input.ToCharArray(); + for (int i = 0; i < c.Length; i++) + { + if (c[i] == 32) + { + c[i] = (char)12288; + continue; + } + + if (c[i] < 127) + { + c[i] = (char)(c[i] + 65248); + } + } + + return new string(c); + } + + /// 转半角的函数(DBC case) + /// 任意字符串 + /// 半角字符串 + /// + /// 全角空格为12288,半角空格为32 + /// 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 + /// + public static string ConvertToDBC(string input) + { + char[] c = input.ToCharArray(); + for (int i = 0; i < c.Length; i++) + { + if (c[i] == 12288) + { + c[i] = (char)32; + continue; + } + + if (c[i] > 65280 && c[i] < 65375) + { + c[i] = (char)(c[i] - 65248); + } + } + + return new string(c); + } + + #endregion 半角全角转换 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/DateTimeHelper.cs b/src/Znyc.Dispatching.Core/Helpers/DateTimeHelper.cs new file mode 100644 index 0000000..57c6c1e --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/DateTimeHelper.cs @@ -0,0 +1,47 @@ +using System; + +namespace Znyc.Dispatching.Core.Helpers +{ + /// + /// DateTime帮助类 + /// + public static class DateTimeHelper + { + /// + /// 判断当前时间是否为今天 + /// + /// + /// + public static bool IsToday(DateTime dt) + { + DateTime today = DateTime.Today; + DateTime tempToday = new DateTime(dt.Year, dt.Month, dt.Day); + return today.Equals(tempToday); + } + + + /// + /// 时间转换 + /// + /// + /// + public static string ToChineseDate(int second) + { + int hour = 0; + int minute = 0; + if (second > 60) + { + minute = second / 60; + second = second % 60; + } + if (minute > 60) + { + hour = minute / 60; + minute = minute % 60; + } + return (hour + "小时" + minute + "分钟" + + second + "秒"); + } + + } +} diff --git a/src/Znyc.Dispatching.Core/Helpers/DatetimeJsonConverter.cs b/src/Znyc.Dispatching.Core/Helpers/DatetimeJsonConverter.cs new file mode 100644 index 0000000..2997be5 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/DatetimeJsonConverter.cs @@ -0,0 +1,74 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Znyc.Dispatching.Core.Helpers +{ + /// + /// 时间类型格式数据处理 + /// + public class DateTimeJsonConverter : JsonConverter + { + /// + /// 时间格式 + /// + private readonly string _dateFormatString; + + /// + /// + public DateTimeJsonConverter() + { + _dateFormatString = "yyyy-MM-dd HH:mm:ss"; + } + + /// + /// + /// 时间格式 + public DateTimeJsonConverter(string dateFormatString) + { + _dateFormatString = dateFormatString; + } + + /// + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + if (DateTime.TryParse(reader.GetString(), out DateTime date)) + { + return date; + } + } + + return reader.GetDateTime(); + } + + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss")); + } + } + + public class DateTimeNullableConverter : JsonConverter + { + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return string.IsNullOrEmpty(reader.GetString()) ? default(DateTime?) : DateTime.Parse(reader.GetString()); + } + + public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) + { + writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss")); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/HtmlHelper.cs b/src/Znyc.Dispatching.Core/Helpers/HtmlHelper.cs new file mode 100644 index 0000000..9797e00 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/HtmlHelper.cs @@ -0,0 +1,70 @@ +using System; +using System.Text.RegularExpressions; + +namespace Znyc.Dispatching.Core.Helpers +{ + + /// + /// + /// + public static class HtmlHelper + { + public static string ReplaceHtmlTag(string html, int length = 0) + { + string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", ""); + strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", ""); + + if (length > 0 && strText.Length > length) + return strText.Substring(0, length); + + return strText; + } + + public static string ReplaceHtmlMark(object Contents) + { + string HtmlString = Convert.ToString(Contents); + string[] RegexString = { + @"style='.*?'", + @"class='.*?'", + @"()?", + @"()?", + @"()?", + @"()?", + @"()?", + @"(

)?", + @"()?", + @"()?", + @"()?", + @"()?", + @"()?", + @"()?", + }; + + + foreach (String str in RegexString) + { + Regex regex = new Regex(str, RegexOptions.IgnoreCase); + HtmlString = regex.Replace(HtmlString, string.Empty); + } + string[] RegexString2 = { + @"", + @"", + @"", + @"

", + @"
", + @"", + @"", + @"", + @" ", + @"", + }; + foreach (String str2 in RegexString2) + { + Regex regex2 = new Regex(str2, RegexOptions.IgnoreCase); + HtmlString = regex2.Replace(HtmlString, string.Empty); + } + return HtmlString; + } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/HttpContextHelper.cs b/src/Znyc.Dispatching.Core/Helpers/HttpContextHelper.cs new file mode 100644 index 0000000..7a63d33 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/HttpContextHelper.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.Http; + +namespace Znyc.Dispatching.Core.Helpers +{ + /// + /// HttpContext帮助类 + /// + public static class HttpContextHelper + { + /// + /// + private static IHttpContextAccessor httpContextAccessor; + + /// + /// + public static HttpContext HttpContext => httpContextAccessor.HttpContext; + + /// + /// 注入 + /// + /// + public static void Configure(IHttpContextAccessor _httpContextAccessor) + { + httpContextAccessor = _httpContextAccessor; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/HttpRequestHelper.cs b/src/Znyc.Dispatching.Core/Helpers/HttpRequestHelper.cs new file mode 100644 index 0000000..1ac7258 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/HttpRequestHelper.cs @@ -0,0 +1,221 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text; + +namespace Znyc.Dispatching.Core.Helpers +{ + /// + /// http请求类 + /// + public static class HttpRequestHelper + { + /// + /// + /// + /// + public static void FillFormDataStream(this Dictionary formData, Stream stream) + { + string dataString = GetQueryString(formData); + byte[] formDataBytes = formData == null ? new byte[0] : Encoding.UTF8.GetBytes(dataString); + stream.Write(formDataBytes, 0, formDataBytes.Length); + stream.Seek(0, SeekOrigin.Begin); //设置指针读取位置 + } + + /// + /// 组装QueryString的方法 + /// 参数之间用&连接,首位没有符号,如:a=1&b=2&c=3 + /// + /// + /// + public static string GetQueryString(this Dictionary formData) + { + if (formData == null || formData.Count == 0) + { + return ""; + } + + StringBuilder sb = new StringBuilder(); + int i = 0; + foreach (KeyValuePair kv in formData) + { + i++; + sb.AppendFormat("{0}={1}", kv.Key, kv.Value); + if (i < formData.Count) + { + sb.Append("&"); + } + } + + return sb.ToString(); + } + + #region 同步方法 + + /// + /// 使用Get方法获取字符串结果 + /// + /// + /// + /// + /// + public static string HttpGet(string url, Encoding encoding = null, int timeOut = 60000) + { + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + request.Method = "GET"; + request.Timeout = timeOut; + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + using (Stream responseStream = response.GetResponseStream()) + { + using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8"))) + { + string retString = myStreamReader.ReadToEnd(); + return retString; + } + } + } + + /// + /// 使用Post方法获取字符串结果,常规提交 + /// + /// + public static string HttpPost(string url, Dictionary formData = null, Encoding encoding = null, + int timeOut = 60000, Dictionary headers = null) + { + MemoryStream ms = new MemoryStream(); + formData.FillFormDataStream(ms); //填充formData + return HttpPost(url, ms, "application/x-www-form-urlencoded", encoding, headers, timeOut); + } + + /// + /// 发送HttpPost请求,使用JSON格式传输数据 + /// + /// + /// + /// + /// + /// + public static string HttpPost(string url, string postData, Encoding encoding = null, + Dictionary headers = null) + { + if (encoding == null) + { + encoding = Encoding.UTF8; + } + + if (string.IsNullOrWhiteSpace(postData)) + { + throw new ArgumentNullException("postData"); + } + + byte[] data = encoding.GetBytes(postData); + MemoryStream stream = new MemoryStream(); + byte[] formDataBytes = postData == null ? new byte[0] : Encoding.UTF8.GetBytes(postData); + stream.Write(formDataBytes, 0, formDataBytes.Length); + stream.Seek(0, SeekOrigin.Begin); //设置指针读取位置 + return HttpPost(url, stream, "application/json", encoding, headers); + } + + /// + /// 使用POST请求数据,使用JSON传输数据 + /// + /// + /// 传输对象,转换为JSON传输 + /// + /// + /// + public static string HttpPost(string url, object dataObj, Encoding encoding = null, + Dictionary headers = null) + { + if (encoding == null) + { + encoding = Encoding.UTF8; + } + + if (dataObj == null) + { + throw new ArgumentNullException("dataObj"); + } + + string postData = JsonConvert.SerializeObject(dataObj, + new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss" }); + byte[] data = encoding.GetBytes(postData); + MemoryStream stream = new MemoryStream(); + byte[] formDataBytes = postData == null ? new byte[0] : Encoding.UTF8.GetBytes(postData); + stream.Write(formDataBytes, 0, formDataBytes.Length); + stream.Seek(0, SeekOrigin.Begin); //设置指针读取位置 + return HttpPost(url, stream, "application/json", encoding, headers); + } + + /// + /// 使用Post方法获取字符串结果 + /// + /// + /// + /// + /// + /// + /// + /// + public static string HttpPost(string url, Stream postStream = null, + string contentType = "application/x-www-form-urlencoded", Encoding encoding = null, + Dictionary headers = null, int timeOut = 60000) + { + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + request.Method = "POST"; + request.Timeout = timeOut; + + request.ContentLength = postStream != null ? postStream.Length : 0; + request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; + request.KeepAlive = false; + + request.UserAgent = + "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.87 Safari/537.36 QQBrowser/9.2.5748.400"; + request.ContentType = contentType; + + if (headers != null) + { + foreach (KeyValuePair header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + #region 输入二进制流 + + if (postStream != null) + { + postStream.Position = 0; + + //直接写入流 + Stream requestStream = request.GetRequestStream(); + + byte[] buffer = new byte[1024]; + int bytesRead = 0; + while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0) + { + requestStream.Write(buffer, 0, bytesRead); + } + + postStream.Close(); //关闭文件访问 + } + + #endregion 输入二进制流 + + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + + using (Stream responseStream = response.GetResponseStream()) + { + using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8"))) + { + string retString = myStreamReader.ReadToEnd(); + return retString; + } + } + } + + #endregion 同步方法 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/MapHelper/DistanceHelper.cs b/src/Znyc.Dispatching.Core/Helpers/MapHelper/DistanceHelper.cs new file mode 100644 index 0000000..a1fb8f0 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/MapHelper/DistanceHelper.cs @@ -0,0 +1,213 @@ +using Newtonsoft.Json; +using System; +using System.IO; +using System.Net; +using System.Text; + +namespace Znyc.Dispatching.Core.Helpers +{ + public class DistanceHelper + { + //根据百度api文档获取两点间最近的行车轨迹距离(非两点的直线距离) + public static decimal GetMileage(decimal originLat, decimal originLng, decimal destinationLat, + decimal destinationLng) + { + //origin_lat = 23.15232300M; + //origin_lng = 113.40876600M; + //destination_lat = 23.06921667M; + //destination_lng = 113.28197816M; + string apiUrl = "http://api.map.baidu.com/routematrix/v2/driving?"; + string apiKey = "tGOVThXXnqNAf0YLCegwSfTzuuYGy8WO"; + string output = "json"; + string origins = originLat + "," + originLng; + string destinations = destinationLat + "," + destinationLng; + string strUrl = string.Format(apiUrl + "output={0}&origins={1}&destinations={2}&tactics=13&&ak={3}", output, + origins, destinations, apiKey); + + HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl); + req.ServicePoint.Expect100Continue = false; + req.Method = "GET"; + req.KeepAlive = true; + req.UserAgent = "Test"; + req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; + + HttpWebResponse rsp = null; + try + { + rsp = (HttpWebResponse)req.GetResponse(); + + if (rsp.CharacterSet != null) + { + Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); + string response = GetResponseAsString(rsp, encoding); + //var aa = JsonHelper.FromJsonTo(response); + Mileage dataReust = JsonConvert.DeserializeObject(response); + if (dataReust.status.Equals("0")) //成功 + { + System.Collections.Generic.List items = dataReust.result; + double distance = 0; + foreach (array item in items) + { + if (item.distance.value > distance) + { + distance = item.distance.value; + } + } + + distance = Math.Round(distance * 1e4) / 1e4 / 1000; //将米转换成公里 + decimal result = Convert.ToDecimal(Math.Round(distance, 2)); //四舍五入两位小数 + return result; + } + + return 30; + } + } + catch (WebException) + { + return 30; + } + + return 30; + } + + /// + /// 把响应流转换为文本。 + /// + /// 响应流对象 + /// 编码方式 + /// 响应文本 + public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) + { + StringBuilder result = new StringBuilder(); + Stream stream = null; + StreamReader reader = null; + + try + { + // 以字符流的方式读取HTTP响应 + stream = rsp.GetResponseStream(); + if (stream != null) + { + reader = new StreamReader(stream, encoding); + } + + // 每次读取不大于256个字符,并写入字符串 + char[] buffer = new char[256]; + int readBytes = 0; + while (reader != null && (readBytes = reader.Read(buffer, 0, buffer.Length)) > 0) + { + result.Append(buffer, 0, readBytes); + } + } + catch (WebException webEx) + { + if (webEx.Status == WebExceptionStatus.Timeout) + { + result = new StringBuilder(); + } + } + finally + { + // 释放资源 + if (reader != null) + { + reader.Close(); + } + + if (stream != null) + { + stream.Close(); + } + + if (rsp != null) + { + rsp.Close(); + } + } + + return result.ToString(); + } + + /// + /// 计算坐标点的距离,直线距离 + /// + /// 开始的纬度 + /// 开始的经度 + /// 结束的纬度 + /// 结束的经度 + /// 距离(公里) + public static decimal GetDistance(double lat1, double lng1, double lat2, double lng2) + { + //法3 + decimal result = 0; + if (!(lat2 < 0.00000001) && lat2 > -0.00000001 && !(lng2 < 0.00000001) && lng2 > -0.00000001) + { + // 地球的半径 + double earthRadius = 6378137.0; //地球半径(米) + Point begin = new Point(lat1, lng1); + Point end = new Point(lat2, lng2); + + double lat = begin.RadLat - end.RadLat; + double lng = begin.RadLng - end.RadLng; + + double dis = 2 * + Math.Asin( + Math.Sqrt(Math.Pow(Math.Sin(lat / 2), 2) + + Math.Cos(begin.RadLat) * Math.Cos(end.RadLat) * + Math.Pow(Math.Sin(lng / 2), 2))); + dis = dis * earthRadius; + dis = Math.Round(dis * 1e4) / 1e4 / 1000; //将米转换成公里 + result = Convert.ToDecimal(Math.Round(dis, 2)); //四舍五入两位小数 + } + + ////法1 + //double pk = 180 / 3.1415926; + //double a1 = lat1 / pk; + //double a2 = lng1 / pk; + //double b1 = lat2 / pk; + //double b2 = lng2 / pk; + //double t1 = Math.Cos(a1) * Math.Cos(a2) * Math.Cos(b1) * Math.Cos(b2); + //double t2 = Math.Cos(a1) * Math.Sin(a2) * Math.Cos(b1) * Math.Sin(b2); + //double t3 = Math.Sin(a1) * Math.Sin(b1); + //double tt = Math.Acos(t1 + t2 + t3); + //return 6366 * tt; + + //法2 + //double la1 = (Math.PI / 180) * lat1; + //double la2 = (Math.PI / 180) * lat2; + + //double lon1 = (Math.PI / 180) * lng1; + //double lon2 = (Math.PI / 180) * lng2; + + //地球半径 + //double R = 6371; + + //两点间距离 km,如果想要米的话,结果*1000就可以了 + //double d = Math.Acos(Math.Sin(la1) * Math.Sin(la2) + Math.Cos(la1) * Math.Cos(la2) * Math.Cos(lon2 - lon1)) * R; + + //return d * 1000; + + return result; + } + + /// + /// 计算两点之间角度 + /// + /// + /// + /// + /// + /// + public static double GetAngle(double lat1, double lng1, double lat2, double lng2) + { + double y = lng2 - lng1; + double x = lat2 - lat1; + + double angle = Math.Atan2(y, x) * 180.0F / Math.PI; + + angle += 180; + + return angle; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapHelper.cs b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapHelper.cs new file mode 100644 index 0000000..68f7413 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapHelper.cs @@ -0,0 +1,353 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using Znyc.Dispatching.Core.MapModel; + +namespace Znyc.Dispatching.Core.Helpers +{ + public static class MapHelper + { + private static readonly double EARTH_RADIUS = 6378.137; + private const string key = "82c0ac5c67dc9b13a3bb5b8fd4813996"; //高德 + + /// + /// 传入经度纬度 + /// + /// 经度 + /// 纬度 + public static string GetLonLatUrl(string lat, string lon) + { + string LonLat = ""; + string url = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=" + lon + "&y=" + lat + ""; + + HttpWebRequest requst = (HttpWebRequest)WebRequest.Create(url); //http传输协议 + HttpWebResponse respone = (HttpWebResponse)requst.GetResponse(); //活的http的网络资源 + Stream stream = respone.GetResponseStream(); //转换成字节流 + StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("utf-8")); //已utf-8模式读取数据 + string responestr = sr.ReadToEnd(); + sr.Close(); + sr.Dispose(); //释放资源 + string[] responeArr = responestr.Split('\"'); + if (responeArr.Length >= 11) + { + LonLat = GetbyBase64("utf-8", responeArr[5]) + "," + GetbyBase64("utf-8", responeArr[9]); + } + + return LonLat; + } + + /// + /// 解析base64信息数据 + /// + /// 解析编码格式 + /// 传入的base64位值 + /// + public static string GetbyBase64(string code_type, string code) + { + string decode = ""; + byte[] bytes = Convert.FromBase64String(code); + try + { + decode = Encoding.GetEncoding(code_type).GetString(bytes); + } + catch + { + decode = code; + } + + return decode; + } + + /// + /// 根据经纬度获取地图信息(高德) + /// + /// 超时时间默认10秒 + /// 经纬度字符串 + /// 失败返回"" + public static MapLocation GetMapLocation(string strLatLng, int timeout = 10000) + { + string url = + string.Format("http://restapi.amap.com/v3/geocode/regeo?key={0}&batch=true&location={1}", + key, strLatLng); + string apiText = HttpGet(url, timeout); + return JObject.Parse(apiText).ToObject(); + + } + + /// + /// 根据经纬度获取地址,多个 + /// + /// 超时时间默认10秒 + /// 经纬度数组 + /// 1、获取详细地址2、获取市跟区 + /// 失败返回"" + public static List GetLocationByLngLat(List lngLatList, int timeout = 10000, + int type = 1) + { + int idx = 0; + List lstAddress = new List(); + List listLatLng = new List(); + try + { + for (int i = 0; i < lngLatList.Count; i++) + { + LocationModel item = lngLatList[i]; + if (idx < 20 && i < lngLatList.Count - 1) + { + listLatLng.Add(item.LngLatStr); + idx++; + } + else + { + if (i == lngLatList.Count - 1) + { + listLatLng.Add(item.LngLatStr); + } + + if (i < lngLatList.Count - 1) + { + i--; //请求地址时,i递增的话会导致每次请求遗漏1个地址 + } + + idx = 0; + string strLatLng = string.Join("|", listLatLng); + MapLocation mapLocation = GetMapLocation(strLatLng); + if (Convert.ToInt32(mapLocation.Status) == 1) + { + switch (type) + { + case 2: + lstAddress.AddRange( + mapLocation.Regeocodes.Select( + x => + x.AddressComponent.City.ToString().Replace("[]", "").Replace("市", "") + + ( + !string.IsNullOrWhiteSpace( + x.AddressComponent.District.ToString().Replace("[]", "")) + ? x.AddressComponent.District.ToString().Replace("[]", "") + : x.AddressComponent.Township.ToString().Replace("[]", "")) + + "|" + x.AddressComponent.Adcode)); + break; + + default: + lstAddress.AddRange( + mapLocation.Regeocodes.Select( + x => x.FormattedAddress.ToString().Replace("[]", ""))); + break; + } + } + else + { + //TODO 当第一个经纬度错误的时候会失败,之后有空回来解决这个问题 + for (int j = 0; j < listLatLng.Count - 1; j++) + { + lstAddress.Add(""); + } + } + + listLatLng = new List(); + } + } + } + catch (Exception) + { + lstAddress = new List { "未知" }; + } + + return lstAddress; + } + + /// + /// 根据经纬度获取地址,一个 + /// + /// + /// + /// 超时时间默认10秒 + /// + /// 失败返回"" + public static string GetLocationByLngLat(decimal longitude = 0, decimal latitude = 0, int type = 1, + int timeout = 10000) + { + string address = ""; + + string strLatLng = longitude + "," + latitude; + + MapLocation mapLocation = GetMapLocation(strLatLng); + + if (Convert.ToInt32(mapLocation.Status) == 1) + { + Regeocode map = mapLocation.Regeocodes.First(); + switch (type) + { + case 2: + address = map.AddressComponent.City.ToString().Replace("[]", "").Replace("市", "") + + (!string.IsNullOrWhiteSpace(map.AddressComponent.District.ToString() + .Replace("[]", "")) + ? map.AddressComponent.District.ToString().Replace("[]", "") + : map.AddressComponent.Township.ToString().Replace("[]", "")) + + "|" + map.AddressComponent.Adcode; + + break; + + default: + address = map.FormattedAddress.ToString().Replace("[]", ""); + break; + } + } + + return address; + } + + + + /// + /// 获取路径规划路线 + /// + /// 起点经度 + /// 起点纬度 + /// 终点经度 + /// 终点纬度 + /// 超时时间默认10秒 + /// 失败返回"" + public static List GetRouteList(decimal startLongitude, decimal startLatitude, + decimal endLongitude, decimal endLatitude, int timeout = 10000) + { + try + { + string origin = startLongitude + "," + startLatitude; + + string destination = endLongitude + "," + endLatitude; + + PathPlanning pathPlanning = GetPathPlanning(origin, destination); + + List list = new List(); + + if (Convert.ToInt32(pathPlanning.Status) == 1) + { + MapModel.Path path = pathPlanning.Routes.Paths.FirstOrDefault(); + if (path != null) + { + string[] lineList = string.Join(";", path.Steps.Select(x => x.Polyline)).Split(';'); + + list.AddRange( + lineList.Select( + x => + new PointLatLng + (Convert.ToDouble(x.Split(',')[1]), Convert.ToDouble(x.Split(',')[0])))); + } + + return list; + } + } + catch (Exception) + { + return new List(); + } + + return new List(); + } + + /// + /// 根据起点终点经纬度获取路径规划(步行)(高德) + /// + /// 终点经纬度 + /// 超时时间默认10秒 + /// 起点经纬度 + /// 失败返回"" + public static PathPlanning GetPathPlanning(string origin, string destination, int timeout = 10000) + { + try + { + string url = + string.Format("https://restapi.amap.com/v3/direction/walking?key={0}&origin={1}&destination={2}", + key, origin, destination); + + string apiText = HttpGet(url, timeout); + return JObject.Parse(apiText).ToObject(); + } + catch (Exception) + { + return new PathPlanning(); + } + } + + public static string HttpGet(string url, int timeout) + { + HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; + req.ContentType = "multipart/form-data"; + req.Accept = "*/*"; + req.UserAgent = ""; + req.Timeout = timeout; + req.Method = "GET"; + req.KeepAlive = true; + HttpWebResponse response = req.GetResponse() as HttpWebResponse; + string apiText = ""; + using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) + { + apiText = sr.ReadToEnd(); + } + + return apiText; + } + + + /** + * 计算两个经纬度之间的距离 + * @param lat1 + * @param lng1 + * @param lat2 + * @param lng2 + * @return + */ + public static double GetDistance(double lat1, double lng1, double lat2, double lng2) + { + double radLat1 = rad(lat1); + double radLat2 = rad(lat2); + double a = radLat1 - radLat2; + double b = rad(lng1) - rad(lng2); + double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2))); + s = s * EARTH_RADIUS; + s = Math.Round(s * 1000); + return s; + } + + + private static double rad(double d) + { + return d * Math.PI / 180.0; + } + + + #region v1.2.7获取路径规划 + /// + /// 根据起点终点经纬度获取路径规划(驾车)(高德) + /// + /// 终点经纬度 + /// 超时时间默认10秒 + /// 起点经纬度 + /// 失败返回"" + public static PathPlanningModel GetPathPlanningByDriving(string origin, string destination, int timeout = 10000) + { + try + { + string url = + string.Format("https://restapi.amap.com/v3/direction/driving?origin={1}&destination={2}&output=json&extensions=base&key={0}", + key, origin, destination); + + string apiText = HttpGet(url, timeout); + return JObject.Parse(apiText).ToObject(); + } + catch (Exception) + { + return new PathPlanningModel(); + } + } + #endregion + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/LocationModel.cs b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/LocationModel.cs new file mode 100644 index 0000000..033d202 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/LocationModel.cs @@ -0,0 +1,20 @@ +namespace Znyc.Dispatching.Core.MapModel +{ + public class LocationModel + { + public LocationModel() + { + } + + public LocationModel(decimal longitude, decimal latitude) + { + Latitude = latitude; + Longitude = longitude; + } + + public decimal Latitude { get; set; } + public decimal Longitude { get; set; } + + public string LngLatStr => Longitude + "," + Latitude; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/MapLocation.cs b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/MapLocation.cs new file mode 100644 index 0000000..5471369 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/MapLocation.cs @@ -0,0 +1,59 @@ +using Newtonsoft.Json; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Core.MapModel +{ + public class MapLocation + { + [JsonProperty("status")] public object Status { get; set; } + + [JsonProperty("info")] public object Info { get; set; } + + [JsonProperty("infocode")] public object Infocode { get; set; } + + [JsonProperty("regeocodes")] public List Regeocodes { get; set; } + + [JsonProperty("regeocode")] public Regeocode Regeocode { get; set; } + } + + public class Regeocode + { + [JsonProperty("formatted_address")] public object FormattedAddress { get; set; } + + [JsonProperty("addressComponent")] public AddressComponent AddressComponent { get; set; } + } + + public class AddressComponent + { + [JsonProperty("country")] public object Country { get; set; } + + [JsonProperty("province")] public object Province { get; set; } + + [JsonProperty("city")] public object City { get; set; } + + [JsonProperty("citycode")] public object Citycode { get; set; } + + [JsonProperty("district")] public object District { get; set; } + + [JsonProperty("adcode")] public object Adcode { get; set; } + + [JsonProperty("township")] public object Township { get; set; } + + [JsonProperty("townCode")] public object TownCode { get; set; } + + [JsonProperty("streetNumber")] public StreetNumber StreetNumber { get; set; } + } + + public class StreetNumber + { + [JsonProperty("street")] public object Street { get; set; } + + [JsonProperty("number")] public object Number { get; set; } + + [JsonProperty("location")] public object Location { get; set; } + + [JsonProperty("direction")] public object Direction { get; set; } + + [JsonProperty("distance")] public object Distance { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/Mileage.cs b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/Mileage.cs new file mode 100644 index 0000000..e8d2fe6 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/Mileage.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Core.Helpers +{ + public class Mileage + { + //public Mileage(string status, string message) + //{ + // this.Status = status; + // this.Message = message; + //} + public List result { get; set; } + + /// + /// + public string status { get; set; } + + /// + /// + public string message { get; set; } + } + + public class array + { + public origin_destination distance { get; set; } + public origin_destination duration { get; set; } + } + + public class origin_destination + { + public string text { get; set; } + public double value { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/PathPlanning.cs b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/PathPlanning.cs new file mode 100644 index 0000000..2eae202 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/PathPlanning.cs @@ -0,0 +1,120 @@ +using Newtonsoft.Json; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Core.MapModel +{ + /// + /// 路径规划实体 + /// + public class PathPlanning + { + /// + /// 返回状态 + /// 值为0或1 1:成功;0:失败 + /// + [JsonProperty("status")] + public object Status { get; set; } + + /// + /// 返回的状态信息 + /// status为0时,info返回错误原;否则返回“OK”。详情参阅info状态表 + /// + [JsonProperty("info")] + public object Info { get; set; } + + /// + /// 返回结果总数目 + /// + [JsonProperty("count")] + public object Count { get; set; } + + /// + /// 路线信息列表 + /// + [JsonProperty("route")] + public Route Routes { get; set; } + } + + public class Route + { + /// + /// 起点坐标 + /// + [JsonProperty("origin")] + public object Origin { get; set; } + + /// + /// 终点坐标 + /// + [JsonProperty("destination")] + public object Destination { get; set; } + + /// + /// 步行方案 + /// + [JsonProperty("paths")] + public List Paths { get; set; } + } + + public class Path + { + /// + /// 起点和终点的步行距离 + /// 单位:米 + /// + [JsonProperty("distance")] + public object Distance { get; set; } + + /// + /// 步行时间预计 + /// 单位:秒 + /// + [JsonProperty("duration")] + public object Duration { get; set; } + + /// + /// 返回步行结果列表 + /// + [JsonProperty("steps")] + public List Steps { get; set; } + } + + public class Step + { + /// + /// 每段步行方案 + /// + [JsonProperty("instruction")] + public object Instruction { get; set; } + + /// + /// 方向 + /// + [JsonProperty("orientation")] + public object Orientation { get; set; } + + /// + /// 道路名称 + /// + [JsonProperty("road")] + public object Road { get; set; } + + /// + /// 此路段距离 + /// + [JsonProperty("distance")] + public object Distance { get; set; } + + /// + /// 此路段预计步行时间 + /// + [JsonProperty("duration")] + public object Duration { get; set; } + + /// + /// 此路段坐标点 + /// + [JsonProperty("polyline")] + public object Polyline { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/PathPlanningModel.cs b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/PathPlanningModel.cs new file mode 100644 index 0000000..00651c1 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/PathPlanningModel.cs @@ -0,0 +1,86 @@ +using System.Collections.Generic; + +namespace Znyc.Dispatching.Core.Helpers +{ + + /// + /// 路径规划实体 + /// + public class PathPlanningModel + { + /// + /// 结果状态值,值为0或1 + /// + public string status { get; set; } + + /// + /// 返回状态说明 + /// + public string info { get; set; } + + + /// + /// + /// + public string infocode { get; set; } + /// + /// 驾车路径规划方案数目 + /// + public string count { get; set; } + + /// + /// 驾车路径规划信息列表 + /// + public Route route { get; set; } + + } + + /// + /// 驾车路径规划信息列表 + /// + public class Route + { + /// + /// 起点坐标 + /// + public string origin { get; set; } + /// + /// 终点坐标 + /// + public string destination { get; set; } + + /// + /// 驾车换乘方案 + /// + public List paths { get; set; } + } + + + /// + /// 驾车换乘方案 + /// + public class Paths + { + /// + /// 行驶距离 + /// + public string distance { get; set; } + + /// + /// 预计行驶时间 + /// + public string duration { get; set; } + + /// + /// 导航策略 + /// + public string strategy { get; set; } + + /// + /// 此导航方案道路收费 + /// + public string tolls { get; set; } + + } +} + diff --git a/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/Point.cs b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/Point.cs new file mode 100644 index 0000000..9c712e6 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/Point.cs @@ -0,0 +1,29 @@ +using System; + +namespace Znyc.Dispatching.Core.Helpers +{ + public class Point + { + /// 纬度 X + /// 经度 Y + public Point(double lat, double lng) + { + Lat = lat; + Lng = lng; + } + + /// + /// 代表纬度 X轴 + /// + public double Lat { set; get; } + + /// + /// 代表经度 Y轴 d + /// + public double Lng { get; set; } + + public double RadLat => Lat * Math.PI / 180; + + public double RadLng => Lng * Math.PI / 180; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/PointLatLng.cs b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/PointLatLng.cs new file mode 100644 index 0000000..00bbb6e --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/MapHelper/MapModel/PointLatLng.cs @@ -0,0 +1,18 @@ +namespace Znyc.Dispatching.Core.MapModel +{ + public class PointLatLng + { + public PointLatLng() + { + } + + public PointLatLng(double lat, double lng) + { + Lat = lat; + Lng = lng; + } + + public double Lat { get; set; } + public double Lng { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/RegexHelper.cs b/src/Znyc.Dispatching.Core/Helpers/RegexHelper.cs new file mode 100644 index 0000000..ec6af20 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/RegexHelper.cs @@ -0,0 +1,257 @@ +using System; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace Znyc.Dispatching.Core.Helpers +{ + + /// + /// 正则帮助类。含大量常用正则表达式。 + /// + public static class RegexHelper + { + /// + /// + /// + /// + /// + public static bool IsMobilePhone(string str) + { + return Regex.IsMatch(str, @"(^0?1[3|4|5|7|8][0-9]\d{8}$)"); + } + /// + /// + /// + /// + /// + public static bool IsBase64String(string str) + { + return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]"); + } + + public static bool IsDate(string date) + { + if (string.IsNullOrEmpty(date)) + { + return false; + } + DateTime minValue = DateTime.MinValue; + return DateTime.TryParse(date, out minValue); + } + + public static bool IsDate(string date, string format) + { + return IsDate(date, format, null, DateTimeStyles.None); + } + + public static bool IsDate(string date, string format, IFormatProvider provider, DateTimeStyles styles) + { + if (string.IsNullOrEmpty(date)) + { + return false; + } + DateTime minValue = DateTime.MinValue; + return DateTime.TryParseExact(date, format, provider, styles, out minValue); + } + + public static bool IsEmail(string email) + { + if (string.IsNullOrEmpty(email)) + { + return false; + } + string pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"; + return Regex.IsMatch(email.Trim(), pattern); + } + /// + /// + /// + /// + /// + public static bool IsGuid(string guid) + { + if (string.IsNullOrEmpty(guid)) + { + return false; + } + return Regex.IsMatch(guid, "[A-F0-9]{8}(-[A-F0-9]{4}){3}-[A-F0-9]{12}|[A-F0-9]{32}", RegexOptions.IgnoreCase); + } + /// + /// + /// + /// + /// + public static bool IsIdCard(string idCard) + { + if (string.IsNullOrEmpty(idCard)) + { + return false; + } + if (idCard.Length == 15) + { + return Regex.IsMatch(idCard, @"^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$"); + } + return ((idCard.Length == 0x12) && Regex.IsMatch(idCard, @"^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[A-Z])$", RegexOptions.IgnoreCase)); + } + /// + /// + /// + /// + /// + public static bool IsInt(object number) + { + if (IsNullOrEmpty(number)) + { + return false; + } + return IsInt(number.ToString()); + } + /// + /// + /// + /// + /// + public static bool IsInt(string number) + { + if (string.IsNullOrEmpty(number)) + { + return false; + } + int result = 0; + return int.TryParse(number, out result); + } + + public static bool IsIP(string ip) + { + if (string.IsNullOrEmpty(ip)) + { + return false; + } + string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"; + return Regex.IsMatch(ip.Trim(), pattern); + } + /// + /// + /// + /// + /// + public static bool IsNullOrEmpty(object data) + { + return ((data == null) || (((data.GetType() == typeof(string)) && string.IsNullOrEmpty(data.ToString().Trim())) || (data.GetType() == typeof(DBNull)))); + } + /// + /// + /// + /// + /// + public static bool IsNumber(object number) + { + if (IsNullOrEmpty(number)) + { + return false; + } + return IsNumber(number.ToString()); + } + /// + /// + /// + /// + /// + public static bool IsNumber(string number) + { + if (string.IsNullOrEmpty(number)) + { + return false; + } + decimal result = 0M; + return decimal.TryParse(number, out result); + } + /// + /// + /// + /// + /// + public static bool IsUrl(string strUrl) + { + return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$", RegexOptions.IgnoreCase); + } + /// + /// 判断是否是mac地址 + /// + /// mac地址字符串 + /// + public static bool IsMacAddress(string mac) + { + return Regex.IsMatch(mac, "^([0-9A-F]{2}-){5}[0-9A-F]{2}$") || Regex.IsMatch(mac, "^[0-9A-F]{12}$"); + } + + /// + /// 获取字节数 + /// str:需要获取的字符串 + /// + public static int Length(string str) + { + if (string.IsNullOrWhiteSpace(str)) + { + return 0; + } + int j = 0; + CharEnumerator ce = str.GetEnumerator(); + while (ce.MoveNext()) + { + j += (ce.Current > 0 && ce.Current < 255) ? 1 : 2; + } + return j; + } + + + /// + /// + /// + /// + public static string[] ReturnPhones(string value) + { + string pattern = @"(^|\s*\+?0?0?86|\D)(1\d{2})[-\s]{0,3}(\d{4})[-\s]{0,3}(\d{4})(?=\D|$)"; + MatchCollection matchCol = Regex.Matches(value.Trim(), pattern); + + string[] result = new string[matchCol.Count]; + if (matchCol.Count > 0) + { + for (int i = 0; i < matchCol.Count; i++) + { + string matchColValue = Regex.Replace(matchCol[i].Value, @"[^0-9]+", ""); + result[i] = matchColValue; + } + } + return result; + } + + /// + /// 判断是否字母 + /// + public static bool IsLetter(string value) + { + if (string.IsNullOrEmpty(value)) + { + return false; + } + string pattern = @"^[a-zA-Z]$"; + return Regex.IsMatch(value.Trim(), pattern); + } + + + /// + /// 判断是否汉字 + /// + public static bool IsChinese(string value) + { + if (string.IsNullOrEmpty(value)) + { + return false; + } + string pattern = @"^[\u4e00-\u9fa5]$"; + return Regex.IsMatch(value.Trim(), pattern); + + } + } +} diff --git a/src/Znyc.Dispatching.Core/Helpers/SmsHelper.cs b/src/Znyc.Dispatching.Core/Helpers/SmsHelper.cs new file mode 100644 index 0000000..4c49bca --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/SmsHelper.cs @@ -0,0 +1,68 @@ +using Furion; +using System; +using System.Threading.Tasks; +using TencentCloud.Common; +using TencentCloud.Common.Profile; +using TencentCloud.Sms.V20190711; +using TencentCloud.Sms.V20190711.Models; + +namespace Znyc.Dispatching.Core.Helpers +{ + /// + /// 短信服务 + /// + public static class SmsHelper + { + /// + /// 发送短信 + /// + /// +86格式 + /// + /// + /// + public static async Task SendSmsAsync(string[] phone, string[] param, string templateId) + { + clientProfile.HttpProfile = httpProfile; + SmsClient client = new SmsClient(cred, App.Configuration["SMSProvider:Region"], clientProfile); + SendSmsRequest req = new SendSmsRequest + { + SmsSdkAppid = App.Configuration["SMSProvider:SmsSdkAppid"], + Sign = App.Configuration["SMSProvider:Sign"], + SenderId = "", + PhoneNumberSet = phone, + TemplateID = templateId, + TemplateParamSet = param + }; + SendSmsResponse rep = await client.SendSms(req); + if (rep.SendStatusSet[0].Code.ToLower() != "ok") + { + return false; + } + + return true; + } + + #region 公共信息 + + private static readonly Credential cred = new() + { + SecretId = App.Configuration["SMSProvider:SecretId"], + SecretKey = App.Configuration["SMSProvider:SecretKey"] + }; + + private static readonly ClientProfile clientProfile = new() + { + SignMethod = ClientProfile.SIGN_TC3SHA256 + }; + + private static readonly HttpProfile httpProfile = new() + { + ReqMethod = "GET", + Timeout = 10, // 请求连接超时时间,单位为秒(默认60秒) + Endpoint = "sms.tencentcloudapi.com", + WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY") + }; + + #endregion 公共信息 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/Snowflake.cs b/src/Znyc.Dispatching.Core/Helpers/Snowflake.cs new file mode 100644 index 0000000..bff6360 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/Snowflake.cs @@ -0,0 +1,155 @@ +using System; + +namespace Znyc.Dispatching.Core.Helpers +{ + public class Snowflake + { + //private const long START_STMP = 1480166465631L; + /*每一部分占用的位数*/ + + //机器标识位数 + private const int MachineIdBits = 5; + + //数据标志位数 + private const int DatacenterIdBits = 5; + + //序列号识位数 + private const int SequenceBits = 12; + + /* 每一部分的最大值*/ + + //机器ID最大值 + private const long MaxMachineNum = -1L ^ (-1L << MachineIdBits); + + //数据标志ID最大值 + private const long MaxDatacenterNum = -1L ^ (-1L << DatacenterIdBits); + + //序列号ID最大值 + private const long MaxSequenceNum = -1L ^ (-1L << SequenceBits); + + /*每一部分向左的位移*/ + + //机器ID偏左移12位 + private const int MachineShift = SequenceBits; + + //数据ID偏左移17位 + private const int DatacenterIdShift = SequenceBits + MachineIdBits; + + //时间毫秒左移22位 + public const int TimestampLeftShift = SequenceBits + MachineIdBits + DatacenterIdBits; + + //基准时间 + private static readonly long StartStmp = 1288834974657L; + + private readonly object _lock = new(); + //public long Sequence = 0L;//序列号 + //{ + // get { return _sequence; } + // internal set { _sequence = value; } + //} + + private readonly DateTime Jan1st1970 = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private long _lastTimestamp = -1L; //上一次时间戳 + + private long _sequence; //序列号 + + public Snowflake(long machineId, long datacenterId) + { + // 如果超出范围就抛出异常 + if (machineId > MaxMachineNum || machineId < 0) + { + throw new ArgumentException(string.Format("machineId 必须大于0,MaxMachineNum: {0}", MaxMachineNum)); + } + + if (datacenterId > MaxDatacenterNum || datacenterId < 0) + { + throw new ArgumentException(string.Format("datacenterId必须大于0,且不能大于MaxDatacenterNum: {0}", + MaxDatacenterNum)); + } + + //先检验再赋值 + MachineId = machineId; + DatacenterId = datacenterId; + //_sequence = sequence; + } + + public long MachineId { get; protected set; } //机器标识 + public long DatacenterId { get; protected set; } //数据中心 + + //public static Init(long machineId, long datacenterId) + //{ + //} + public long NextId() + { + lock (_lock) + { + long timestamp = TimeGen(); + if (timestamp < _lastTimestamp) + { + throw new Exception(string.Format("时间戳必须大于上一次生成ID的时间戳. 拒绝为{0}毫秒生成id", _lastTimestamp - timestamp)); + } + + //如果上次生成时间和当前时间相同,在同一毫秒内 + if (_lastTimestamp == timestamp) + { + //sequence自增,和sequenceMask相与一下,去掉高位 + _sequence = (_sequence + 1) & MaxSequenceNum; + //判断是否溢出,也就是每毫秒内超过1024,当为1024时,与sequenceMask相与,sequence就等于0 + if (_sequence == 0L) + { + //等待到下一毫秒 + timestamp = TilNextMillis(_lastTimestamp); + } + } + else + { + //如果和上次生成时间不同,重置sequence,就是下一毫秒开始,sequence计数重新从0开始累加, + //为了保证尾数随机性更大一些,最后一位可以设置一个随机数 + _sequence = 0L; //new Random().Next(10); + } + + _lastTimestamp = timestamp; + return ((timestamp - StartStmp) << TimestampLeftShift) | (DatacenterId << DatacenterIdShift) | + (MachineId << MachineShift) | _sequence; + } + } + + // 防止产生的时间比之前的时间还要小(由于NTP回拨等问题),保持增量的趋势. + protected virtual long TilNextMillis(long lastTimestamp) + { + long timestamp = TimeGen(); + while (timestamp <= lastTimestamp) + { + timestamp = TimeGen(); + } + + return timestamp; + } + + // 获取当前的时间戳 + protected virtual long TimeGen() + { + //return TimeExtensions.CurrentTimeMillis(); + return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds; + } + } + + public class IdWorkerHelper + { + private static readonly Snowflake _idWorker; + + static IdWorkerHelper() + { + _idWorker = new Snowflake(1, 1); + } + + private IdWorkerHelper() + { + } + + public static long GenId64() + { + return _idWorker.NextId(); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/StringHelper.cs b/src/Znyc.Dispatching.Core/Helpers/StringHelper.cs new file mode 100644 index 0000000..120a603 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/StringHelper.cs @@ -0,0 +1,244 @@ +using hyjiacan.py4n; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Core.Helpers +{ + /// + /// 字符串帮助类 + /// + public static class StringHelper + { + private static readonly char[] _constant = + { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' + }; + + + /// + /// 生成随机字符串,默认32位 + /// + /// 随机数长度 + /// + public static string GenerateRandom(int length = 32) + { + StringBuilder newRandom = new StringBuilder(); + Random rd = new Random(); + for (int i = 0; i < length; i++) + { + newRandom.Append(_constant[rd.Next(_constant.Length)]); + } + + return newRandom.ToString(); + } + + /// + /// 生成随机字符串,只包含数字 + /// + /// + /// + public static string GenerateRandomNumber(int length = 6) + { + StringBuilder newRandom = new StringBuilder(); + Random rd = new Random(); + for (int i = 0; i < length; i++) + { + newRandom.Append(_constant[rd.Next(10)]); + } + + return newRandom.ToString(); + } + + public static string Format(string str, object obj) + { + if (str.IsNull()) + { + return str; + } + + string s = str; + if (obj.GetType().Name == "JObject") + { + foreach (KeyValuePair item in (JObject)obj) + { + string k = item.Key; + string v = item.Value.ToString(); + s = Regex.Replace(s, "\\{" + k + "\\}", v, RegexOptions.IgnoreCase); + } + } + else + { + foreach (PropertyInfo p in obj.GetType().GetProperties()) + { + string xx = p.Name; + string yy = p.GetValue(obj).ToString(); + s = Regex.Replace(s, "\\{" + xx + "\\}", yy, RegexOptions.IgnoreCase); + } + } + + return s; + } + + /// + /// 隐藏手机号 + /// + /// + /// + public static string ConvertPhoneNo(string Phone) + { + return Regex.Replace(Phone, "(\\d{3})\\d{4}(\\d{4})", "$1****$2"); + } + + /// + /// 隐藏身份证号 + /// + /// + /// + public static string ConvertIdCard(string idCard) + { + return Regex.Replace(idCard, "(\\d{6})\\d{8}(\\w{4})", "$1********$2"); + } + + public static string ToChineseMainlandForPhone(this string phone) + { + return string.Format("+86{0}", phone); + } + + /// + /// 计算时间间隔 + /// + /// + /// + public static string ShowTimeInterval(DateTime? startTime) + { + TimeSpan ts = DateTime.Now - startTime.ToDateTime(); + string time = ""; + if (ts.Days > 0) + { + time = string.Format(ts.Days + "天" + ts.Hours + "小时" + ts.Minutes + "分钟"); + } + + if (ts.Hours > 0 && ts.Days == 0) + { + time = string.Format(ts.Hours + "小时" + ts.Minutes + "分钟"); + } + + if (ts.Hours == 0 && ts.Days == 0) + { + time = string.Format(ts.Minutes + "分钟"); + } + + return time; + } + + /// + /// 将对象属性转换为key-value对 + /// + /// + /// + public static Dictionary ToMap(object o) + { + Dictionary map = new Dictionary(); + Type t = o.GetType(); + PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); + foreach (PropertyInfo p in pi) + { + MethodInfo mi = p.GetGetMethod(); + if (mi != null && mi.IsPublic) + { + map.Add(p.Name, mi.Invoke(o, new object[] { }).ToString()); + } + } + + return map; + } + + + + + + + + /// + /// 返回首字母 + /// + /// + /// + /// 获得字符串首字符字母(大写); + /// + /// + /// + public static string GetStringFirstSpell(string cnChar) + { + //除字母、数字、汉字以外的返回"*" + var result = "#"; + + if (string.IsNullOrEmpty(cnChar.Trim())) + return result; + + + cnChar = cnChar.Trim().Substring(0, 1); + var firstName = cnChar; + + byte[] arrCn = Encoding.Default.GetBytes(cnChar); + + //首字为字符,占一个字节 + if (arrCn.Length <= 1) + { + //大写英文字母 + if ((short)arrCn[0] >= 65 && (short)arrCn[0] <= 90) + return cnChar; + + //小写英文字母 + if (arrCn[0] >= 97 && arrCn[0] <= 122) + return Encoding.Default.GetString(new byte[] { (byte)((short)arrCn[0] - 32) }); + + //数字 + switch (cnChar) + { + case "1": + result = "Y"; + break; + case "2": + result = "E"; + break; + case "3": + case "4": + result = "S"; + break; + case "5": + result = "W"; + break; + case "0": + case "6": + result = "L"; + break; + case "7": + result = "Q"; + break; + case "8": + result = "B"; + break; + case "9": + result = "J"; + break; + } + return result; + } + else if (!RegexHelper.IsChinese(firstName)) + { + return "#"; + } + //首字为汉字,占两个字节 + else + { + return GetStringFirstSpell(Pinyin4Net.GetFirstPinyin(char.Parse(cnChar))); + } + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/TimeHelper.cs b/src/Znyc.Dispatching.Core/Helpers/TimeHelper.cs new file mode 100644 index 0000000..3abc582 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/TimeHelper.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Znyc.Dispatching.Core.Helpers +{ + public static class TimeHelper + { + /// + /// 比较两个时间相差的分钟 + /// + /// 开始时间 + /// 结束时间 + /// 返回(分钟) + public static int ExecDateDiff(DateTime dateBegin, DateTime dateEnd) + { + TimeSpan ts1 = new TimeSpan(dateBegin.Ticks); + TimeSpan ts2 = new TimeSpan(dateEnd.Ticks); + TimeSpan ts3 = ts1.Subtract(ts2).Duration(); + //你想转的格式 + return Convert.ToInt32(ts3.TotalMinutes); + } + + /// + /// 时间差格式转换 + /// + /// 时间差 + /// 精确度,默认为2 + /// + public static string TimeSpanFormat(TimeSpan ts, int accuracy = 2) + { + StringBuilder sb = new StringBuilder(); + int idx = 0; + if (ts.Days != 0 && idx < accuracy) + { + sb.Append(ts.Days + "天"); + idx++; + } + + if (ts.Hours != 0 && idx < accuracy) + { + sb.Append(ts.Hours + "小时"); + idx++; + } + + if (ts.Minutes != 0 && idx < accuracy) + { + sb.Append(ts.Minutes + "分"); + idx++; + } + + if (ts.Seconds != 0 && idx < accuracy) + { + sb.Append(ts.Seconds + "秒"); + } + + return sb.ToString(); + } + + /// + /// 获取时间格式(yyyy-MM-dd HH:mm:ss) + /// + /// + /// + public static string ToDateTimeFormat(this DateTime? dateTime) + { + return dateTime == null ? "" : Convert.ToDateTime(dateTime).ToString("yyyy-MM-dd HH:mm:ss"); + } + + /// + /// 获取时间格式(yyyy-MM-dd HH:mm:ss) + /// + /// + /// + public static string ToDateTimeFormat(this DateTime dateTime) + { + return Convert.ToDateTime(dateTime).ToString("yyyy-MM-dd HH:mm:ss"); + } + + /// + /// 得到时间戳 + /// + /// + public static long ConvertToTimestamp(this DateTime time) + { + DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1)); + long times = (int)(time - startTime).TotalSeconds; + return times; + } + + /// + /// 得到时间戳 + /// + /// + public static long ConvertToTimestamp(this DateTime? time) + { + if (time == null) + { + return 0; + } + + DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1)); + long times = (int)(Convert.ToDateTime(time) - startTime).TotalSeconds; + return times; + } + + /// + /// 获取某段日期范围内的所有日期 + /// + /// 开始日期 + /// 结束日期 + /// + public static List FindDates(DateTime startTime, DateTime endTime) + { + List listDays = new List(); + DateTime dtDay = new DateTime(); + for (dtDay = startTime; dtDay.CompareTo(endTime) <= 0; dtDay = dtDay.AddDays(1)) + { + listDays.Add(dtDay); + } + + return listDays; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/UploadHelper.cs b/src/Znyc.Dispatching.Core/Helpers/UploadHelper.cs new file mode 100644 index 0000000..e0ddffc --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/UploadHelper.cs @@ -0,0 +1,132 @@ +using COSXML; +using COSXML.Auth; +using COSXML.Transfer; +using Furion.FriendlyException; +using Microsoft.AspNetCore.Http; +using NLog; +using System; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Core.Helpers +{ + public class UploadHelper + { + /// + /// 上传单文件 + /// + /// + /// + /// + /// + public async Task UploadAsync(IFormFile file, UploadOptions config, + CancellationToken cancellationToken = default) + { + FileInfo res = new FileInfo(); + + if (file == null || file.Length < 1) + { + throw Oops.Oh("请上传文件!"); + } + + //格式限制 + if (!config.Avatar.ContentType.Contains(file.ContentType)) + { + throw Oops.Oh("文件格式错误"); + } + + //大小限制 + if (!(file.Length <= config.Avatar.MaxSize)) + { + throw Oops.Oh("文件过大"); + } + + FileInfo fileInfo = new FileInfo(file.FileName, file.Length) + { + UploadPath = config.Avatar.UploadPath, + RequestPath = config.Avatar.RequestPath + }; + fileInfo.RelativePath = Path.Combine().ToPath(); + if (!Directory.Exists(fileInfo.FileDirectory)) + { + Directory.CreateDirectory(fileInfo.FileDirectory); + } + + fileInfo.SaveName = $"{IdWorkerHelper.GenId64()}.{fileInfo.Extension}"; + + bool result = await SaveAsync(file, fileInfo.FilePath, cancellationToken, config); + return fileInfo; + } + + /// + /// 保存文件 + /// + /// + /// + /// + /// + /// + public async Task SaveAsync(IFormFile file, string filePath, CancellationToken cancellationToken, + UploadOptions config) + { + using (FileStream stream = new FileStream(filePath, FileMode.Create)) + { + await file.CopyToAsync(stream, cancellationToken); + } + + bool result = await SaveCosAsync(filePath, config); + File.Delete(filePath); + return result; + } + + /// + /// 保存文件 + /// + /// + /// + /// + public async Task SaveCosAsync(string filePath, UploadOptions uploadConfig) + { + Logger logger = LogManager.GetCurrentClassLogger(); + + try + { + QCloudCredentialProvider cosCredentialProvider = + new DefaultQCloudCredentialProvider( + uploadConfig.SecretId, uploadConfig.SecretKey, 600); + CosXmlConfig config = new CosXmlConfig.Builder() + .IsHttps(true) + .SetRegion(uploadConfig.Region) + .SetDebugLog(true) + .Build(); + CosXml cosXml = new CosXmlServer(config, cosCredentialProvider); + TransferConfig transferConfig = new TransferConfig(); + TransferManager transferManager = new TransferManager(cosXml, transferConfig); + string bucket = uploadConfig.Bucket; //存储桶, + string cosPath = Path.GetFileName(filePath); + string srcPath = filePath; + COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath); + uploadTask.SetSrcPath(srcPath); + COSXMLUploadTask.UploadTaskResult result = await transferManager.UploadAsync(uploadTask); + if (result.httpCode != 200) + { + return false; + } + } + catch (Exception ex) + { + logger.Error(ex.InnerException); + return false; + } + finally + { + LogManager.Shutdown(); + } + + return true; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/UtilConvert.cs b/src/Znyc.Dispatching.Core/Helpers/UtilConvert.cs new file mode 100644 index 0000000..67ad89e --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/UtilConvert.cs @@ -0,0 +1,252 @@ +using System; +using System.Text; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.Core.Helpers +{ + /// + /// 数据类型转换 + /// + public static class UtilConvert + { + public static int ToInt(this object thisValue) + { + int reval = 0; + if (thisValue == null) + { + return 0; + } + + if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + + return reval; + } + + public static int ToInt(this object thisValue, int errorValue) + { + if (thisValue != null && thisValue != DBNull.Value && + int.TryParse(thisValue.ToString(), out int reval)) + { + return reval; + } + + return errorValue; + } + + public static long ToLong(this object s) + { + if (s == null || s == DBNull.Value) + { + return 0L; + } + + long.TryParse(s.ToString(), out long result); + return result; + } + + public static double ToMoney(this object thisValue) + { + if (thisValue != null && thisValue != DBNull.Value && + double.TryParse(thisValue.ToString(), out double reval)) + { + return reval; + } + + return 0; + } + + public static double ToMoney(this object thisValue, double errorValue) + { + if (thisValue != null && thisValue != DBNull.Value && + double.TryParse(thisValue.ToString(), out double reval)) + { + return reval; + } + + return errorValue; + } + + public static string ToString(this object thisValue) + { + if (thisValue != null) + { + return thisValue.ToString().Trim(); + } + + return ""; + } + + public static string ToString(this object thisValue, string errorValue) + { + if (thisValue != null) + { + return thisValue.ToString().Trim(); + } + + return errorValue; + } + + /// + /// 转换成Double/Single + /// + /// + /// 小数位数 + /// + public static double ToDouble(this object s, int? digits = null) + { + if (s == null || s == DBNull.Value) + { + return 0d; + } + + double.TryParse(s.ToString(), out double result); + + if (digits == null) + { + return result; + } + + return Math.Round(result, digits.Value); + } + + public static decimal ToDecimal(this object thisValue) + { + if (thisValue != null && thisValue != DBNull.Value && + decimal.TryParse(thisValue.ToString(), out decimal reval)) + { + return reval; + } + + return 0; + } + + public static decimal ToDecimal(this object thisValue, decimal errorValue) + { + if (thisValue != null && thisValue != DBNull.Value && + decimal.TryParse(thisValue.ToString(), out decimal reval)) + { + return reval; + } + + return errorValue; + } + + public static DateTime ToDateTime(this object thisValue) + { + DateTime reval = DateTime.MinValue; + if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) + { + reval = Convert.ToDateTime(thisValue); + } + + return reval; + } + + public static DateTime ToDateTime(this object thisValue, DateTime errorValue) + { + if (thisValue != null && thisValue != DBNull.Value && + DateTime.TryParse(thisValue.ToString(), out DateTime reval)) + { + return reval; + } + + return errorValue; + } + + public static DateTime ToDateTime(this long milliseconds) + { + return DateTimeExtensions.TimestampStart.AddMilliseconds(milliseconds); + } + + public static bool ToBool(this object thisValue) + { + bool reval = false; + if (thisValue != null && thisValue != DBNull.Value && + bool.TryParse(thisValue.ToString().ToLower(), out reval)) + { + return reval; + } + + return reval; + } + + public static byte ToByte(this object s) + { + if (s == null || s == DBNull.Value) + { + return 0; + } + + byte.TryParse(s.ToString(), out byte result); + return result; + } + + #region ==字节转换== + + /// + /// 转换为16进制 + /// + /// + /// 是否小写 + /// + public static string ToHex(this byte[] bytes, bool lowerCase = true) + { + if (bytes == null) + { + return null; + } + + StringBuilder result = new StringBuilder(); + string format = lowerCase ? "x2" : "X2"; + for (int i = 0; i < bytes.Length; i++) + { + result.Append(bytes[i].ToString(format)); + } + + return result.ToString(); + } + + /// + /// 16进制转字节数组 + /// + /// + /// + public static byte[] HexToBytes(this string s) + { + if (s.IsNull()) + { + return null; + } + + byte[] bytes = new byte[s.Length / 2]; + + for (int x = 0; x < s.Length / 2; x++) + { + int i = Convert.ToInt32(s.Substring(x * 2, 2), 16); + bytes[x] = (byte)i; + } + + return bytes; + } + + /// + /// 转换为Base64 + /// + /// + /// + public static string ToBase64(this byte[] bytes) + { + if (bytes == null) + { + return null; + } + + return Convert.ToBase64String(bytes); + } + + #endregion ==字节转换== + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Helpers/XSSHelper.cs b/src/Znyc.Dispatching.Core/Helpers/XSSHelper.cs new file mode 100644 index 0000000..cf3048b --- /dev/null +++ b/src/Znyc.Dispatching.Core/Helpers/XSSHelper.cs @@ -0,0 +1,28 @@ +using Ganss.XSS; + +namespace Znyc.Dispatching.Core.Helpers +{ + public class XSSHelper + { + private HtmlSanitizer sanitizer; + public XSSHelper() + { + sanitizer = new HtmlSanitizer(); + //sanitizer.AllowedTags.Add("div");//标签白名单 + sanitizer.AllowedAttributes.Add("class");//标签属性白名单,默认没有class标签属性 + //sanitizer.AllowedCssProperties.Add("font-family");//CSS属性白名单 + } + + /// + /// XSS过滤 + /// + /// html代码 + /// 过滤结果 + public string Filter(string html) + { + string str = sanitizer.Sanitize(html); + return str; + } + } + +} diff --git a/src/Znyc.Dispatching.Core/HostedService/LogHostedService.cs b/src/Znyc.Dispatching.Core/HostedService/LogHostedService.cs new file mode 100644 index 0000000..d13a407 --- /dev/null +++ b/src/Znyc.Dispatching.Core/HostedService/LogHostedService.cs @@ -0,0 +1,130 @@ +using Furion.DatabaseAccessor; +using Microsoft.Extensions.Hosting; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.SimpleQueue; + +namespace Znyc.Dispatching.Core +{ + /// + /// 后台日志写入服务 + /// + public class LogHostedService : IHostedService + { + private readonly IConcurrentQueue _logExQueue; + + private readonly IRepository _LogExRepository; + private readonly IConcurrentQueue _logOpQueue; + private readonly IRepository _LogOpRepository; + private readonly IConcurrentQueue _logVisQueue; + private readonly IRepository _LogVisRepository; + + public LogHostedService( + IConcurrentQueue logExQueue, + IConcurrentQueue logOpQueue, + IConcurrentQueue logVisQueue) + { + _logExQueue = logExQueue; + _logOpQueue = logOpQueue; + _logVisQueue = logVisQueue; + _LogExRepository = Db.GetRepository(); + _LogOpRepository = Db.GetRepository(); + _LogVisRepository = Db.GetRepository(); + } + + /// + /// 任务开始 + /// + /// + /// + public Task StartAsync(CancellationToken cancellationToken) + { + Task.Run(DoWork, cancellationToken); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } + + /// + /// 工作线程 + /// + private async Task DoWork() + { + // 日志暂存器,待写入 + List LogExs = new(); + List LogOps = new(); + List LogViss = new(); + while (true) + { + // 取系统配置,获得轮训间隔和单次写入容量 + int interval = 5000; + int quantity = 100; + + // 后台队列中产生了日志,取出写入暂存器 + int logExCount = _logExQueue.Count(); + if (logExCount > 0) + { + for (int i = 0; i < logExCount; i++) + { + if (_logExQueue.Try(out LogEx obj)) + { + LogExs.Add(obj); + } + } + } + + int logOpCount = _logOpQueue.Count(); + if (logOpCount > 0) + { + for (int i = 0; i < logOpCount; i++) + { + if (_logOpQueue.Try(out LogOp obj)) + { + LogOps.Add(obj); + } + } + } + + int logVisCount = _logVisQueue.Count(); + if (logVisCount > 0) + { + for (int i = 0; i < logVisCount; i++) + { + if (_logVisQueue.Try(out LogVis obj)) + { + LogViss.Add(obj); + } + } + } + + // 达到系统配置的容量则写入数据库 + if (LogExs.Count > quantity) + { + await _LogExRepository.InsertNowAsync(LogExs); + LogExs.Clear(); + } + + if (LogOps.Count > quantity) + { + await _LogOpRepository.InsertNowAsync(LogOps); + LogOps.Clear(); + } + + if (LogViss.Count > quantity) + { + await _LogVisRepository.InsertNowAsync(LogViss); + LogViss.Clear(); + } + + // 执行间隔 + await Task.Delay(interval); + } + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Manager/IUserManager.cs b/src/Znyc.Dispatching.Core/Manager/IUserManager.cs new file mode 100644 index 0000000..6afe38a --- /dev/null +++ b/src/Znyc.Dispatching.Core/Manager/IUserManager.cs @@ -0,0 +1,13 @@ +namespace Znyc.Dispatching.Core +{ + public interface IUserManager + { + string Account { get; } + long UserId { get; } + string UserName { get; } + long RoleId { get; } + long CompanyId { get; } + + bool SuperAdmin { get; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Manager/UserManager.cs b/src/Znyc.Dispatching.Core/Manager/UserManager.cs new file mode 100644 index 0000000..31d5df4 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Manager/UserManager.cs @@ -0,0 +1,129 @@ +using Furion.DependencyInjection; +using Microsoft.AspNetCore.Http; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Helpers; + +namespace Znyc.Dispatching.Core +{ + /// + /// 用户管理 + /// + public class UserManager : IUserManager, IScoped + { + private readonly IHttpContextAccessor _httpContextAccessor; + + + public UserManager(IHttpContextAccessor httpContextAccessor) + { + _httpContextAccessor = httpContextAccessor; + } + + /// + /// 用户Id + /// + public virtual long UserId + { + get + { + System.Security.Claims.Claim id = _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimConst.CLAINM_USERID); + if (id != null && id.Value.NotNull()) + { + return id.Value.ToLong(); + } + + return 0; + } + } + + /// + /// 权限Id + /// + public long RoleId + { + get + { + System.Security.Claims.Claim roleId = _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimConst.CLAINM_ROLEID); + + if (roleId != null && roleId.Value.NotNull()) + { + return roleId.Value.ToLong(); + } + + return 0; + } + } + + /// + /// 昵称 + /// + public string UserName + { + get + { + System.Security.Claims.Claim userName = _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimConst.CLAINM_USERNAME); + + if (userName != null && userName.Value.NotNull()) + { + return userName.Value; + } + + return ""; + } + } + + + /// + /// CompanyId + /// + public long CompanyId + { + get + { + System.Security.Claims.Claim companyId = _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimConst.CLAINM_COMPANYID); + + if (companyId != null && companyId.Value.NotNull()) + { + return companyId.Value.ToLong(); + } + + return 0; + } + } + + /// + /// Account + /// + public string Account + { + get + { + System.Security.Claims.Claim name = _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimConst.CLAINM_ACCOUNT); + + if (name != null && name.Value.NotNull()) + { + return name.Value; + } + + return ""; + } + } + + /// + /// SessionKey + /// + public bool SuperAdmin + { + get + { + System.Security.Claims.Claim superAdmin = _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimConst.CLAINM_SUPERADMIN); + + if (superAdmin != null && superAdmin.Value.NotNull()) + { + return superAdmin.Value.ToBool(); + } + + return false; + } + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Options/RefreshTokenSettingOptions.cs b/src/Znyc.Dispatching.Core/Options/RefreshTokenSettingOptions.cs new file mode 100644 index 0000000..67fe7f5 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Options/RefreshTokenSettingOptions.cs @@ -0,0 +1,15 @@ +using Furion.ConfigurableOptions; + +namespace Znyc.Dispatching.Core.Options +{ + /// + /// 刷新令牌设置 + /// + public sealed class RefreshTokenSettingOptions : IConfigurableOptions + { + /// + /// 令牌过期时间(分钟) + /// + public int ExpiredTime { get; set; } = 43200; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Rpc/IHttp.cs b/src/Znyc.Dispatching.Core/Rpc/IHttp.cs new file mode 100644 index 0000000..d7fc629 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Rpc/IHttp.cs @@ -0,0 +1,11 @@ +using Furion.RemoteRequest; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Core.Rpc +{ + public interface IHttp : IHttpDispatchProxy + { + [Get("https://api.apishop.net/common/weather/get15DaysWeatherByArea")] + Task GetXXXAsync(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/SimpleQueue/IConcurrentQueue.cs b/src/Znyc.Dispatching.Core/SimpleQueue/IConcurrentQueue.cs new file mode 100644 index 0000000..f040a5d --- /dev/null +++ b/src/Znyc.Dispatching.Core/SimpleQueue/IConcurrentQueue.cs @@ -0,0 +1,13 @@ +namespace Znyc.Dispatching.Core.SimpleQueue +{ + public interface IConcurrentQueue + { + void Add(T obj); + + bool Try(out T obj); + + int Count(); + + void Clear(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/SimpleQueue/SimpleQueue.cs b/src/Znyc.Dispatching.Core/SimpleQueue/SimpleQueue.cs new file mode 100644 index 0000000..6a77e46 --- /dev/null +++ b/src/Znyc.Dispatching.Core/SimpleQueue/SimpleQueue.cs @@ -0,0 +1,55 @@ +using System.Collections.Concurrent; +using Znyc.Dispatching.Core.SimpleQueue; + +namespace Znyc.Dispatching.Core +{ + /// + /// 简单泛型队列 + /// + /// + public class SimpleQueue : IConcurrentQueue + { + private static ConcurrentQueue _simpleQueue; + + public SimpleQueue() + { + _simpleQueue = new ConcurrentQueue(); + } + + /// + /// 新增 + /// + /// + public void Add(T obj) + { + _simpleQueue.Enqueue(obj); + } + + /// + /// 取出 + /// + /// + /// + public bool Try(out T obj) + { + return _simpleQueue.TryDequeue(out obj); + } + + /// + /// 总数 + /// + /// + public int Count() + { + return _simpleQueue.Count; + } + + /// + /// 清理 + /// + public void Clear() + { + _simpleQueue.Clear(); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/SqlProxy/Company/ICompanySql .cs b/src/Znyc.Dispatching.Core/SqlProxy/Company/ICompanySql .cs new file mode 100644 index 0000000..a80104b --- /dev/null +++ b/src/Znyc.Dispatching.Core/SqlProxy/Company/ICompanySql .cs @@ -0,0 +1,25 @@ +using Furion.DatabaseAccessor; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Entitys; + +namespace Znyc.Dispatching.Core +{ + /// + /// sql高级代理 + /// + public interface ICompanySql : ISqlDispatchProxy + { + // 获取所有公司 + [SqlExecute("select * from dc_company where IsDeleted=0")] + Task> GetCompanyList(); + + // 带参数查询 + [SqlExecute("select * from dc_company where id >@id and name like @name")] + Company GetCompanyList(int id, string name); + + //单行单列 + [SqlExecute("select Name from dc_company where id = @id")] + Task GetValueAsync(int id); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Util/OSSClientUtil.cs b/src/Znyc.Dispatching.Core/Util/OSSClientUtil.cs new file mode 100644 index 0000000..c041850 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Util/OSSClientUtil.cs @@ -0,0 +1,300 @@ +using Aliyun.OSS; +using Aliyun.OSS.Common; +using System; +using System.IO; +using System.Net; + +namespace Znyc.Dispatching.Core +{ + /// + /// 阿里云oss文件上传工具类 + /// + public class OSSClientUtil + { + private const string + _endpoint = + "oss-cn-beijing.aliyuncs.com"; //"oss-cn-beijing.aliyuncs.com";// "oss-cn-huhehaote-internal.aliyuncs.com";//"oss-cn-huhehaote.aliyuncs.com" ; + + private static readonly string _accessKeyId = "accessKeyId"; + private static readonly string _accessKeySecret = "accessKeySecret"; + + //const string endpoint = "oss-cn-huhehaote-internal.aliyuncs.com"; + private static readonly string _internalEndpoint = "internalEndpoint"; //内网传输连接 + private static readonly string _bucketName = "bucketName"; + + public static OssClient GetClient() + { + return new(_endpoint, _accessKeyId, _accessKeySecret); + } + + public static OssClient GetClient_CND() + { + ClientConfiguration conf = new ClientConfiguration + { + IsCname = true + }; + return new OssClient("cdnmedia.aliyuncs.com", _accessKeyId, _accessKeySecret, conf); + } + + public static OssClient GetClient_internal() + { + return new(_internalEndpoint, _accessKeyId, _accessKeySecret); + } + + /// + /// 上传本地文件(走阿里云内网传输) + /// + /// + /// + /// + public static bool PushMedia_internal(string objectName, string localFilename) + { + OssClient client = GetClient_internal(); + return client.PutObject(_bucketName, objectName, localFilename).HttpStatusCode == HttpStatusCode.OK; + } + + /// + /// 上传一个图片 + /// + /// 图片经过base64加密后的结果 + /// 文件名,例如:Emplyoee/dzzBack.jpg + public static bool PushImg(string base64Code, string fileName) + { + OssClient client = GetClient(); + MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Code)); + return client.PutObject(_bucketName, fileName, stream).HttpStatusCode == HttpStatusCode.OK; + } + + public static bool PushMedia(Stream stream, string fileName) + { + OssClient client = GetClient(); + return client.PutObject(_bucketName, fileName, stream).HttpStatusCode == HttpStatusCode.OK; + } + + /// + /// 上传本地文件 + /// + /// + /// + /// 返回参数说明 1.本地文件不存在 2.文件oss上已存在 3.上传失败 4.上传成功 + /// + public static int PushMedia(string objectName, string localFilename) + { + if (!File.Exists(localFilename)) + { + return 1; + } + + if (DoesObjectExist(objectName)) + { + return 2; // 存在文件 + } + + try + { + OssClient client = GetClient(); + //MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Code)); + //var metadata = new ObjectMetadata(); + //metadata.ContentType = TypeTo(contentType); + + if (localFilename.Contains("http")) + { + WebClient webClient = new WebClient { Credentials = CredentialCache.DefaultCredentials }; + byte[] stream = webClient.DownloadData(localFilename); + MemoryStream ms = new MemoryStream(stream); + PutObjectResult c = client.PutObject(_bucketName, objectName, ms); + if (c.HttpStatusCode == HttpStatusCode.OK) + { + return 4; + } + + return 3; + } + else + { + PutObjectResult c = client.PutObject(_bucketName, objectName, localFilename); + if (c.HttpStatusCode == HttpStatusCode.OK) + { + return 4; + } + + return 3; + } + } + catch + { + return 3; + } + } + + /// + /// 上传一个图片 + /// + /// 图片字节 + /// 文件名,例如:Emplyoee/dzzBack.jpg + /// + public static bool PushImg(byte[] filebyte, string fileName, out string md5) + { + OssClient client = GetClient(); + MemoryStream stream = new MemoryStream(filebyte, 0, filebyte.Length); + PutObjectResult result = client.PutObject(_bucketName, fileName, stream); + md5 = result.ResponseMetadata["Content-MD5"]; + return result.HttpStatusCode == HttpStatusCode.OK; + } + + /// + /// 获取鉴权后的URL,URL有效日期默认一小时 + /// + /// 文件名,例如:Emplyoee/dzzBack.jpg + /// + public static string GetImg(string fileName) + { + OssClient client = GetClient(); + string key = fileName; + GeneratePresignedUriRequest req = new GeneratePresignedUriRequest(_bucketName, key, SignHttpMethod.Get) + { + Expiration = DateTime.Now.AddHours(1) + }; + return client.GeneratePresignedUri(req).ToString(); + } + + /// + /// 获取鉴权后的URL + /// + /// 文件名,例如:Emplyoee/dzzBack.jpg + /// URL有效日期,例如:DateTime.Now.AddHours(1) + /// + public static string GetImg(string fileName, DateTime expiration) + { + OssClient client = GetClient(); + string key = fileName; + GeneratePresignedUriRequest req = new GeneratePresignedUriRequest(_bucketName, key, SignHttpMethod.Get) + { + Expiration = expiration + }; + return client.GeneratePresignedUri(req).ToString(); + } + + /// + /// 将文件转换成byte[] 数组 + /// + /// 文件路径文件名称 + /// byte[] + private byte[] AuthGetFileData(string fileUrl) + { + using (FileStream fs = new FileStream(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + byte[] buffur = new byte[fs.Length]; + using (BinaryWriter bw = new BinaryWriter(fs)) + { + bw.Write(buffur); + bw.Close(); + } + + return buffur; + } + } + + /// + /// 删除文件 + /// + /// 文件id + /// 文件url + public static bool DeletefileCode(string fileCode) + { + if (string.IsNullOrEmpty(fileCode)) + { + return true; + } + + //检查fileCode磁盘中是否存在此文件 + if (File.Exists(fileCode)) + { + File.Delete(fileCode); + return true; + } + + OssClient client = GetClient(); + client.DeleteObject(_bucketName, fileCode); + return true; + } + + /// + /// 删除文件夹 + /// + /// 文件id + /// 文件url + public static bool DeleteFolder(string prefix) + { + if (string.IsNullOrEmpty(prefix)) + { + return true; + } + + OssClient client = GetClient(); + ListObjectsRequest listObjectsRequest = new ListObjectsRequest(_bucketName) + { + Prefix = prefix + }; + ObjectListing result = client.ListObjects(listObjectsRequest); + + foreach (OssObjectSummary summary in result.ObjectSummaries) + { + client.DeleteObject(_bucketName, summary.Key); + } + + return false; + } + + /// + /// 判断文件是否存在 + /// + /// + /// + public static bool DoesObjectExist(string fileName) + { + OssClient client = GetClient(); + // 判断文件是否存在。 + bool exist = client.DoesObjectExist(_bucketName, fileName); + return exist; + } + + /// + /// 类型转换 + /// + /// + public static string TypeTo(string type) + { + type = type switch + { + "mp4" => "video/mp4", + "mp3" => "audio/mp3", + _ => "image/" + type + }; + return type; + } + + public static OssObject DownLoad(string fileName) + { + //var client = GetClient(); + //DateTime expiration = new DateTime().AddHours(1); + //GeneratePresignedUriRequest request = new GeneratePresignedUriRequest(bucketName, fileName, SignHttpMethod.Get); + //// 设置过期时间。 + //request.Expiration=expiration; + //// 生成签名URL(HTTP GET请求)。 + //Uri signedUrl = client.GeneratePresignedUri(request); + + //// 添加GetObject请求头。 + ////customHeaders.put("Range", "bytes=100-1000"); + //OssObject result = client.GetObject(signedUrl); + + OssClient client = GetClient(); + string key = fileName; + _ = new GeneratePresignedUriRequest(_bucketName, key, SignHttpMethod.Get) + { + Expiration = DateTime.Now.AddHours(1) + }; + return client.GetObject(_bucketName, key); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Util/ReflectionUtil.cs b/src/Znyc.Dispatching.Core/Util/ReflectionUtil.cs new file mode 100644 index 0000000..4179aef --- /dev/null +++ b/src/Znyc.Dispatching.Core/Util/ReflectionUtil.cs @@ -0,0 +1,26 @@ +using System; +using System.Reflection; + +namespace Znyc.Dispatching.Core +{ + /// + /// 反射工具 + /// + public static class ReflectionUtil + { + /// + /// 获取字段特性 + /// + /// + /// + /// + public static T GetDescriptionValue(this FieldInfo field) where T : Attribute + { + // 获取字段的指定特性,不包含继承中的特性 + object[] customAttributes = field.GetCustomAttributes(typeof(T), false); + + // 如果没有数据返回null + return customAttributes.Length > 0 ? (T)customAttributes[0] : null; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Znyc.Dispatching.Core.csproj b/src/Znyc.Dispatching.Core/Znyc.Dispatching.Core.csproj new file mode 100644 index 0000000..e96f8ea --- /dev/null +++ b/src/Znyc.Dispatching.Core/Znyc.Dispatching.Core.csproj @@ -0,0 +1,46 @@ + + + + net6.0 + 1701;1702;1591 + Znyc.Dispatching.Core.xml + + + + + + + + + + + Always + + + Always + + + Always + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/Znyc.Dispatching.Core.xml b/src/Znyc.Dispatching.Core/Znyc.Dispatching.Core.xml new file mode 100644 index 0000000..39f06a9 --- /dev/null +++ b/src/Znyc.Dispatching.Core/Znyc.Dispatching.Core.xml @@ -0,0 +1,4995 @@ + + + + Znyc.Dispatching.Core + + + + + 缓存配置 + + + + + Redis配置 + + + + + 缓存接口 + + + + + 用于在 key 存在时删除 key + + 键 + + + + 用于在 key 存在时删除 key + + 键 + + + + + 用于在 key 模板存在时删除 + + key模板 + + + + + 检查给定 key 是否存在 + + 键 + + + + + 检查给定 key 是否存在 + + 键 + + + + + 获取指定 key 的值 + + 键 + + + + + 获取指定 key 的值 + + byte[] 或其他类型 + 键 + + + + + 获取指定 key 的值 + + 键 + + + + + 获取指定 key 的值 + + byte[] 或其他类型 + 键 + + + + + 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 + + 键 + 值 + + + + 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 + + 键 + 值 + 有效期 + + + + 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 + + 键 + 值 + + + + + 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 + + 键 + 值 + 有效期 + + + + + 获取所有缓存 + + + + + + 缓存壳 + + + + + + + + + + 缓存壳 + + + + + + + + + + 发布 + + + + + + + + 订阅 + + + + + + + Redis缓存 + + + + + 缓存壳 + + + + + + + + + + 缓存壳 + + + + + + + + + + 发布 + + + + + + + + 订阅 + + + + + + + 发布 + + + + + + + + 发送短信配置 + + + + + 上传配置 + + + + + 头像上传配置 + + + + + 文档图片上传配置 + + + + + 文件上传配置 + + + + + 上传路径 + + + + + 请求路径 + + + + + 读取路径 + + + + + 路径格式 + + + + + 路径日期格式 + + + + + 文件大小 10M = 10 * 1024 * 1024 + + + + + 最大允许上传个数 -1不限制 + + + + + 文件格式 + + + + + 微信配置 + + + + + 是否调试模式 + + + + + 小程序 + + + + + + + + + + + + + + + + + + + + + + + + + 公众号 + + + + + 公众号 + + + + + + + + + 用户 + + + + + 日志 + + + + + 系统中心 + + + + + 用户Id + + + + + 账号 + + + + + 名称 + + + + + 是否超级管理 + + + + + 角色Id + + + + + 公司Id + + + + + 默认密码 + + + + + 默认超速速度 + + + + + 默认停留标示Id + + + + + 默认角色Id + + + + + 默认角色名称 + + + + + 车主人员默认首页路径 + + + + + 外租伙伴默认首页路径 + + + + + 管理员默认首页路径 + + + + + 默认加密盐 + + + + + mongoDB超速报警表前缀 + + + + + 用户缓存 + + + + + 菜单缓存 + + + + + 权限缓存 + + + + + 数据范围缓存 + + + + + 验证码缓存 + + + + + 角色缓存 + + + + + 角色菜单缓存 + + + + + 车辆类型缓存 + + + + + 车辆分组缓存 + + + + + 字典缓存 + + + + + 默认logo地址 + + + + + 头像地址前缀 + + + + + 默认头像地址 + + + + + 默认头像全部地址 + + + + + 公司缓存 + + + + + JWT + + + + + token + + + + + 公司车辆缓存 + + + + + 车辆缓存 + + + + + 车辆GPS信息缓存 + + + + + 超速记录缓存 + + + + + 员工缓存 + + + + + 员工列表缓存 + + + + + 未读报警消息 + + + + + 轨迹回放 + + + + + 车场列表缓存 + + + + + 车场缓存 + + + + + 工程列表缓存 + + + + + 工程缓存 + + + + + 车组人员缓存 + + + + + + + + + + + + + + + 订单签证地址 + + + + + + + + + + 公司表 + + + + + 公司名称 + + + + + 公司Logo + + + + + 联系人 + + + + + 联系人电话 + + + + + 精度 + + + + + 纬度 + + + + + 地址 + + + + + 审核时间 + + + + + 状态(字典 0正常 1停用 2删除) + + + + + 停留标示Id + + + + + 一键派工是否显示工程名称 + + + + + 调度角色是否有添加工程名称的权限 + + + + + 是否启用任务车型选项,默认为关 + + + + + 施工单位表 + + + + + 所属公司 + + + + + 施工单位 + + + + + 联系人 + + + + + 联系电话 + + + + + 状态 + + + + + 自定义实体基类 + + + + + 自定义实体基类 + + + + + 主键Id + + + + + 创建时间 + + + + + 更新时间 + + + + + 创建者Id + + + + + 修改者Id + + + + + 软删除 + + + + + 数据字典表 + + + + + 字典父级 + + + + + 字典编码 + + + + + 字典值 + + + + + 字典描述 + + + + + 字典名称 + + + + + 是否启用 + + + + + 字典排序 + + + + + 员工表 + + + + + 用户Id + + + + + 员工头像 + + + + + 员工名 + + + + + 手机号 + + + + + 机构Id + + + + + CommonStatus + + + + + RoleStatus + + + + + RoleStatus + + + + + 是否默认登录 + + + + + 系统操作/审计日志表 + + + + + 表名 + + + + + 列名 + + + + + 新值 + + + + + 旧值 + + + + + 操作人Id + + + + + 操作人名称 + + + + + 操作方式:新增、更新、删除 + + + + + 异常日志 + + + + + 操作人 + + + + + 名称 + + + + + 类名 + + + + + 方法名 + + + + + 异常名称 + + + + + 异常信息 + + + + + 异常源 + + + + + 堆栈信息 + + + + + 参数对象 + + + + + 异常时间 + + + + + 操作日志表 + + + + + 名称 + + + + + 是否执行成功(Y-是,N-否) + + + + + 具体消息 + + + + + IP + + + + + 地址 + + + + + 浏览器 + + + + + 操作系统 + + + + + 请求地址 + + + + + 类名称 + + + + + 方法名称 + + + + + 请求方式(GET POST PUT DELETE) + + + + + 请求参数 + + + + + 返回结果 + + + + + 耗时(毫秒) + + + + + 操作时间 + + + + + 操作人 + + + + + 访问日志表 + + + + + 名称 + + + + + 是否执行成功(Y-是,N-否) + + + + + 具体消息 + + + + + IP + + + + + 地址 + + + + + 浏览器 + + + + + 操作系统 + + + + + 访问类型 + + + + + 访问时间 + + + + + 访问人 + + + + + 菜单表 + + + + + 父Id + + + + + 所属层级 + + + + + 名称 + + + + + 编码 + + + + + 菜单类型(字典 0目录 1菜单 2按钮) + + + + + 图标 + + + + + 路由地址 + + + + + 权限标识 + + + + + 是否外链 + + + + + 是否展开 + + + + + 是否显示 + + + + + 排序 + + + + + 详细描述 + + + + + CommonStatus + + + + + 多对多(角色) + + + + + 多对多中间表(用户角色) + + + + + 上级 + + + + + 子集 + + + + + 配置实体关系 + + + + + + + + 站内消息表 + + + + + 发送者Id + + + + + 消息标题 + + + + + 消息类型 + + + + + 发送类型 + + + + + 组Id + + + + + 消息内容 + + + + + 发送时间 + + + + + 消息记录表 + + + + + 接收者Id + + + + + 消息Id + + + + + 状态 + + + + + 站内消息 + + + + + 油耗表 + + + + + 公司Id + + + + + 加油日期 + + + + + 车辆Id + + + + + 车俩编号 + + + + + 加油单号 + + + + + 加油量 + + + + + 油单价 + + + + + 金额 + + + + + 派工订单表 + + + + + 公司Id + + + + + 车辆Id,,冗余查询车辆列表状态 + + + + + 车辆编号 + + + + + 到场时间 + + + + + 经度 + + + + + 纬度 + + + + + 地址 + + + + + 状态,10=待指派,20=已指派,未接单,30=已接单,40=已出发,50=已完成,60=已签单,70=已离开,80=已评价,101=撤销 + + + + + 工程Id + + + + + 工程名称 + + + + + 业务员Id + + + + + 订单来源,10=录入,20=报单 + + + + + 订单内容 + + + + + 是否外请车 + + + + + 指派时间 + + + + + 指派人 + + + + + 接单时间 + + + + + 出发时间 + + + + + 到达时间 + + + + + 签单时间 + + + + + 完成时间 + + + + + 评价时间 + + + + + 离开时间 + + + + + 到家时间 + + + + + 车组人员 + + + + + 任务车型 + + + + + 施工单位 + + + + + 派工订单车组人员表 + + + + + 订单Id + + + + + 指派任务人员Id + + + + + 姓名 + + + + + 电话 + + + + + 是否司机 + + + + + 订单签证表 + + + + + 订单Id + + + + + 图片路径 + + + + + 工程信息表 + + + + + 所属公司 + + + + + 工程名称 + + + + + 业务员Id + + + + + 经度 + + + + + 纬度 + + + + + 地址 + + + + + 是否启用 + + + + + 施工单位 + + + + + 施工单位名称 + + + + + 工程信息联系人表 + + + + + 工程Id + + + + + 联系人Id,链接员工表Id + + + + + 联系人姓名 + + + + + 联系人电话 + + + + + 意见反馈表 + + + + + 投诉人Id + + + + + 投诉内容 + + + + + 投诉时间 + + + + + 举报状态 + + + + + 处理状态 + + + + + 处理结果 + + + + + 角色表 + + + + + 名称 + + + + + 编码 + + + + + 角色说明 + + + + + 状态(字典 0正常 1停用 2删除) + + + + + 角色菜单表 + + + + + 角色Id + + + + + 菜单Id + + + + + 业务员 + + + + + 业务员姓名 + + + + + 业务员电话 + + + + + 是否启用 + + + + + 用户表 + + + + + OpenId + + + + + 头像 + + + + + 用户名 + + + + + 电话 + + + + + 状态 + + + + + 用户角色表 + + + + + 用户Id + + + + + 系统角色Id + + + + + 车场表 + + + + + 用户Id + + + + + 车场Id + + + + + 公司Id + + + + + 是否默认 + + + + + 车辆表 + + + + + 所属公司 + + + + + 车辆编号 + + + + + 车牌号 + + + + + 车辆类型 + + + + + 所属车组 + + + + + SIM卡号 + + + + + 设备类型 + + + + + 设备号 + + + + + GPS协议号 + + + + + 是否激活 + + + + + 是否开启GPS + + + + + 所属司机 + + + + + 司机电话 + + + + + 联系人 + + + + + 联系电话 + + + + + IEML号 + + + + + 状态 + + + + + 打火状态 + + + + + 工作状态 + + + + + Gps状态 + + + + + GPS时间 + + + + + 开通时间 + + + + + 到期时间 + + + + + 物联卡类型 + + + + + 是否开启超速报警 + + + + + 超速速度 + + + + + 排序 + + + + + 车辆表分组 + + + + + 公司Id + + + + + 名称 + + + + + 父级权限Id + + + + + 状态(字典 0正常 1停用 2删除) + + + + + 车组人员信息表 + + + + + 公司Id + + + + + 车组人员Id + + + + + 员工名 + + + + + 手机号 + + + + + 是否司机 + + + + + 车辆类型表 + + + + + 公司Id + + + + + 名称 + + + + + 父级权限Id + + + + + 状态(字典 0正常 1停用 2删除) + + + + + 微信中间表 + + + + + UnionId + + + + + OpenId + + + + + 用户Id + + + + + 公众号OpenId + + + + + 车场表 + + + + + 公司Id + + + + + 联系人 + + + + + 联系人电话 + + + + + 精度 + + + + + 纬度 + + + + + 地址 + + + + + 状态(字典 1正常 0停用 -1删除) + + + + + 打火状态 + + + + + 关闭 + + + + + 正常打火 + + + + + 公共状态 + + + + + 正常 + + + + + 停用 + + + + + 删除 + + + + + 审核中 + + + + + 数据操作类型 + + + + + 其它 + + + + + 增加 + + + + + 删除 + + + + + 编辑 + + + + + 更新 + + + + + 查询 + + + + + 详情 + + + + + 树 + + + + + 导入 + + + + + 导出 + + + + + 授权 + + + + + 强退 + + + + + 清空 + + + + + 修改状态 + + + + + 系统错误码 + + + + + 用户名或密码不正确 + + + + + 非法操作!禁止删除自己 + + + + + 记录不存在 + + + + + 账号已存在 + + + + + 旧密码不匹配 + + + + + 测试数据禁止更改admin密码 + + + + + 数据已存在 + + + + + 数据不存在或含有关联引用,禁止删除 + + + + + 禁止为管理员分配角色 + + + + + 重复数据或记录含有不存在数据 + + + + + 禁止为超级管理员角色分配权限 + + + + + 非法数据 + + + + + Id不能为空 + + + + + 所属机构不在自己的数据范围内 + + + + + 禁止删除超级管理员 + + + + + 禁止修改超级管理员状态 + + + + + 没有权限 + + + + + 账号已冻结 + + + + + 验证码错误 + + + + + 账号不存在 + + + + + 公司审核中 + + + + + 验证码失效 + + + + + 新密码不一致 + + + + + 父机构不存在 + + + + + 当前机构Id不能与父机构Id相同 + + + + + 已有相同组织机构,编码或名称相同 + + + + + 没有权限操作机构 + + + + + 该机构下有员工禁止删除 + + + + + 附属机构下有员工禁止删除 + + + + + 只能增加下级机构 + + + + + 字典类型不存在 + + + + + 字典类型已存在 + + + + + 字典类型下面有字典值禁止删除 + + + + + 字典值已存在 + + + + + 字典值不存在 + + + + + 字典状态错误 + + + + + 菜单已存在 + + + + + 路由地址为空 + + + + + 打开方式为空 + + + + + 权限标识格式为空 + + + + + 权限标识格式错误 + + + + + 权限不存在 + + + + + 父级菜单不能为当前节点,请重新选择父级菜单 + + + + + 不能移动根节点 + + + + + 已存在同名或同编码应用 + + + + + 默认激活系统只能有一个 + + + + + 该应用下有菜单禁止删除 + + + + + 已存在同名或同编码应用 + + + + + 已存在同名或同编码职位 + + + + + 该职位下有员工禁止删除 + + + + + 通知公告状态错误 + + + + + 通知公告删除失败 + + + + + 通知公告编辑失败 + + + + + 文件不存在 + + + + + 已存在同名或同编码参数配置 + + + + + 禁止删除系统参数 + + + + + 已存在同名任务调度 + + + + + 任务调度不存在 + + + + + 演示环境禁止修改数据 + + + + + 已存在同名或同主机租户 + + + + + 该表代码模板已经生成过 + + + + + 该类型不存在 + + + + + 该字段不存在 + + + + + 该类型不是枚举类型 + + + + + 该实体不存在 + + + + + 父菜单不存在 + + + + + 已存在同名或同编码项目 + + + + + 已存在相同证件号码人员 + + + + + 检测数据不存在 + + + + + JsCode不存在 + + + + + 账号已存在 + + + + + 文件存储位置 + + + + + 阿里云 + + + + + 腾讯云 + + + + + minio服务器 + + + + + 本地 + + + + + Gps状态 + + + + + 离线 + + + + + 行驶 + + + + + 静止 + + + + + 默认 + + + + + 接口 + + + + + 网站 + + + + + 循环时间 + + + + + HTTP状态码 + + + + + 客户端可能继续其请求 + + + + + 正在更改协议版本或协议 + + + + + 请求成功,且请求的信息包含在响应中 + + + + + 请求导致在响应被发送前创建新资源 + + + + + 请求已被接受做进一步处理 + + + + + 返回的元信息来自缓存副本而不是原始服务器,因此可能不正确 + + + + + 已成功处理请求并且响应已被设定为无内容 + + + + + 客户端应重置(或重新加载)当前资源 + + + + + 响应是包括字节范围的 GET请求所请求的部分响应 + + + + + 请求的信息有多种表示形式,默认操作是将此状态视为重定向 + + + + + 请求的信息已移到 Location头中指定的 URI 处 + + + + + 请求的信息位于 Location 头中指定的 URI 处 + + + + + 将客户端自动重定向到 Location 头中指定的 URI + + + + + 客户端的缓存副本是最新的 + + + + + 请求应使用位于 Location 头中指定的 URI 的代理服务器 + + + + + 服务器未能识别请求 + + + + + 请求的资源要求身份验证 + + + + + 需要付费 + + + + + 服务器拒绝满足请求 + + + + + 请求的资源不在服务器上 + + + + + 请求的资源上不允许请求方法(POST或 GET) + + + + + 客户端已用 Accept 头指示将不接受资源的任何可用表示形式 + + + + + 请求的代理要求身份验证 + Proxy-authenticate 头包含如何执行身份验证的详细信息 + + + + + 客户端没有在服务器期望请求的时间内发送请求 + + + + + 由于服务器上的冲突而未能执行请求 + + + + + 请求的资源不再可用 + + + + + 缺少必需的 Content-length + + + + + 为此请求设置的条件失败,且无法执行此请求 + 条件是用条件请求标头(如 If-Match、If-None-Match 或 If-Unmodified-Since)设置的。 + + + + + 请求太大,服务器无法处理 + + + + + URI 太长 + + + + + 请求是不支持的类型 + + + + + 无法返回从资源请求的数据范围,因为范围的开头在资源的开头之前,或因为范围的结尾在资源的结尾之后 + + + + + 服务器未能符合Expect头中给定的预期值 + + + + + 服务器拒绝处理客户端使用当前协议发送的请求,但是可以接受其使用升级后的协议发送的请求 + + + + + 服务器上发生了一般错误 + + + + + 服务器不支持请求的函数 + + + + + 中间代理服务器从另一代理或原始服务器接收到错误响应 + + + + + 服务器暂时不可用,通常是由于过多加载或维护 + + + + + 中间代理服务器在等待来自另一个代理或原始服务器的响应时已超时 + + + + + 服务器不支持请求的HTTP版本 + + + + + 登陆类型 + + + + + 登陆 + + + + + 登出 + + + + + 注册 + + + + + 改密 + + + + + 三方授权登陆 + + + + + 系统菜单类型 + + + + + 目录 + + + + + 菜单 + + + + + 按钮 + + + + + 通知公告用户状态 + + + + + 未读 + + + + + 已读 + + + + + 派工订单来源 + + + + + 录入 + + + + + 报单 + + + + + 派工状态 + + + + + 草稿 + + + + + 待指派 + + + + + 已指派(未接单) + + + + + 已接单 + + + + + 已出发 + + + + + 已到达 + + + + + 已完成 + + + + + 已签单 + + + + + 已离开 + + + + + 已评价 + + + + + 撤销 + + + + + 已到家 + + + + + 人才招聘 + + + + + 派工调度 + + + + + 后台管理系统 + + + + + 查询类型的枚举 + + + + + 等于 + + + + + 模糊 + + + + + 大于 + + + + + 小于 + + + + + 不等于 + + + + + 大于等于 + + + + + 小于等于 + + + + + 不为空 + + + + + http请求类型 + + + + + 执行内部方法 + + + + + GET请求 + + + + + POST请求 + + + + + PUT请求 + + + + + DELETE请求 + + + + + 角色类型 + + + + + 车组人员 + + + + + 调度 + + + + + 销售 + + + + + 财务 + + + + + 管理员 + + + + + 业务员 + + + + + 车队长 + + + + + 仓管 + + + + + 工地施工员 + + + + + 外租伙伴 + + + + + 兼职业务 + + + + + 停留点状态 + + + + + 起点 + + + + + 停留点 + + + + + 终点 + + + + + 产品类型 + + + + + 博实结KG_M08四线 + + + + + 工作状态 + + + + + 关闭 + + + + + 正常工作 + + + + + 菜单激活类型 + + + + + 是 + + + + + 否 + + + + + 时间戳起始日期 + + + + + 转换为时间戳 + + + 是否使用毫秒 + + + + + 获取周几 + + + + + + + 字典扩展 + + + + + 将一个字典转化为 QueryString + + + + + + + + 将一个字符串 URL 编码 + + + + + + + 移除空值项 + + + + + + 枚举扩展 + + + + + 获取枚举对象Key与名称的字典(缓存) + + + + + + + 获取枚举对象Key与名称的字典 + + + + + + + 获取枚举类型key与描述的字典(缓存) + + + + + + + + 获取枚举类型key与描述的字典(没有描述则获取name) + + + + + + + + 从程序集中查找指定枚举类型 + + + + + + + + 从程序集中加载所有枚举类型 + + + + + + + 从枚举中获取Description + + 需要获取枚举描述的枚举 + 描述内容 + + + + 根据 value 值获取Description + + + + + + + + 根据 value 值获取Description + + + + + + + + 获取字段Description + + FieldInfo + DescriptionAttribute[] + + + + 获取枚举所有名称 + + 枚举类型typeof(T) + 枚举名称列表 + + + + 获取所有枚举对应的值 + + 枚举类型typeof(T) + 枚举值列表 + + + + 获取枚举名以及对应的Description + + 枚举类型typeof(T) + 返回Dictionary ,Key为枚举名, Value为枚举对应的Description + + + + 获取枚举名以及对应的Value + + 枚举类型typeof(T) + 返回Dictionary ,Key为描述名, Value为枚举对应的值 + + + + 通用输入扩展参数(带权限) + + + + + 授权菜单 + + + + + 授权角色 + + + + + 授权数据 + + + + + 通用分页输入参数 + + + + + 搜索值 + + + + + 当前页码 + + + + + 页码容量 + + + + + 搜索开始时间 + + + + + 搜索结束时间 + + + + + 排序字段 + + + + + 排序方法,默认升序,否则降序(配合antd前端,约定参数为 Ascend,Dscend) + + + + + 降序排序(不要问我为什么是descend不是desc,前端约定参数就是这样) + + + + + 判断对象是否为空 + + + + + + + 判断对象是否不为空 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 获取当前时间的时间戳 + + + + + + + 判断字符串是否为Null、空 + + + + + + + 判断字符串是否不为Null、空 + + + + + + + 与字符串进行比较,忽略大小写 + + + + + + + + 首字母转小写 + + + + + + + 首字母转大写 + + + + + + + 转为Base64,UTF-8格式 + + + + + + + 转为Base64 + + + 编码 + + + + + 通用输入帮助类 + + + + + 排序方式(默认降序) + + + 是否降序 + + + + + 规范化RESTful风格返回值 + + + + + 异常返回值 + + + + + + + + 成功返回值 + + + + + + + + 验证失败返回值 + + + + + + + + 处理输出状态码 + + + + + + + + + RESTful风格---XIAONUO返回格式 + + + + + + 执行成功 + + + + + 状态码 + + + + + 错误信息 + + + + + 数据 + + + + + 附加数据 + + + + + 时间戳 + + + + + 分页列表结果 + + + + + + 文件信息 + + + + + 初始化文件信息 + + 文件名称 + 大小 + + + + 上传路径 + + + + + 请求路径 + + + + + 相对路径 + + + + + 文件名 + + + + + 保存名 + + + + + 文件大小 + + + + + 扩展名 + + + + + 文件目录 + + + + + 文件请求路径 + + + + + 文件相对路径 + + + + + 文件路径 + + + + + 文件大小 + + + + + 初始化文件大小 + + 文件大小 + 文件大小单位 + + + + 文件字节长度 + + + + + 获取文件大小,单位:字节 + + + + + 获取文件大小,单位:K + + + + + 获取文件大小,单位:M + + + + + 获取文件大小,单位:G + + + + + 输出描述 + + + + + 文件大小单位 + + + + + 字节 + + + + + K字节 + + + + + M字节 + + + + + G字节 + + + + + 全局异常处理 + + + + + 请求日志拦截 + + + + + 遍历修改类的字符串属性 + + 类名 + 数据类型 + 对象 + + + + + byte转换类 + + + + + 将对象转换为byte数组 + + 被转换对象 + 转换后byte数组 + + + + 将byte数组转换成对象 + + 被转换byte数组 + 转换完成后的对象 + + + + 将byte数组转换成对象 + + 被转换byte数组 + 转换完成后的对象 + + + + 保留小数点后六位 + + + + + + + 处理数据类型转换,数制转换、编码转换相关的类 + + + + + 将byte[]转换成int + + 需要转换成整数的byte数组 + + + + 实现各进制数间的转换。ConvertBase("15",10,16)表示将十进制数15转换为16进制的数。 + + 要转换的值,即原值 + 原值的进制,只能是2,8,10,16四个值。 + 要转换到的目标进制,只能是2,8,10,16四个值。 + + + + 判断是否是 2 8 10 16 + + + + + + + 将string转换成byte[] + + 要转换的字符串 + + + + 使用指定字符集将string转换成byte[] + + 要转换的字符串 + 字符编码 + + + + 将byte[]转换成string + + 要转换的字节数组 + + + + 使用指定字符集将byte[]转换成string + + 要转换的字节数组 + 字符编码 + + + + 将数据转换为整型 转换失败返回默认值 + + 数据类型 + 数据 + 默认值 + + + + + 将数据转换为整型 转换失败返回默认值 + + 数据 + 默认值 + + + + + 将数据转换为整型 转换失败返回默认值 + + 数据 + 默认值 + + + + + 将数据转换为布尔类型 转换失败返回默认值 + + 数据类型 + 数据 + 默认值 + + + + + 将数据转换为布尔类型 转换失败返回 默认值 + + 数据 + 默认值 + + + + + 将数据转换为布尔类型 转换失败返回 默认值 + + 数据 + 默认值 + + + + + 将数据转换为单精度浮点型 转换失败 返回默认值 + + 数据类型 + 数据 + 默认值 + + + + + 将数据转换为单精度浮点型 转换失败返回默认值 + + 数据 + 默认值 + + + + + 将数据转换为单精度浮点型 转换失败返回默认值 + + 数据 + 默认值 + + + + + 将数据转换为双精度浮点型 转换失败返回默认值 + + 数据的类型 + 要转换的数据 + 默认值 + + + + + 将数据转换为双精度浮点型,并设置小数位 转换失败返回默认值 + + 数据的类型 + 要转换的数据 + 小数的位数 + 默认值 + + + + + 将数据转换为双精度浮点型 转换失败返回默认值 + + 要转换的数据 + 默认值 + + + + + 将数据转换为双精度浮点型 转换失败返回默认值 + + 要转换的数据 + 默认值 + + + + + 将数据转换为双精度浮点型,并设置小数位 转换失败返回默认值 + + 要转换的数据 + 小数的位数 + 默认值 + + + + + 将数据转换为双精度浮点型,并设置小数位 转换失败返回默认值 + + 要转换的数据 + 小数的位数 + 默认值 + + + + + 将数据转换为指定类型 + + 转换的数据 + 转换的目标类型 + + + + 将数据转换为指定类型 + + 转换的目标类型 + 转换的数据 + + + + + + + + + + + + + + + + + + + 将数据转换为Decimal 转换失败返回默认值 + + 数据类型 + 数据 + 默认值 + + + + + 将数据转换为Decimal 转换失败返回 默认值 + + 数据 + 默认值 + + + + + 将数据转换为Decimal 转换失败返回 默认值 + + 数据 + 默认值 + + + + + 将数据转换为DateTime 转换失败返回默认值 + + 数据类型 + 数据 + 默认值 + + + + + 将数据转换为DateTime 转换失败返回 默认值 + + 数据 + 默认值 + + + + + 将数据转换为DateTime 转换失败返回 默认值 + + 数据 + 默认值 + + + + + 转全角的函数(SBC case) + + 任意字符串 + 全角字符串 + + 全角空格为12288,半角空格为32 + 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 + + + + 转半角的函数(DBC case) + 任意字符串 + 半角字符串 + + 全角空格为12288,半角空格为32 + 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 + + + + + DateTime帮助类 + + + + + 判断当前时间是否为今天 + + + + + + + 时间转换 + + + + + + + 时间类型格式数据处理 + + + + + 时间格式 + + + + + + + + + + 时间格式 + + + + + + + + + + + + + + + + + + + + + + + + HttpContext帮助类 + + + + + + + + + + + + + 注入 + + + + + + http请求类 + + + + + + + + + + + 组装QueryString的方法 + 参数之间用&连接,首位没有符号,如:a=1&b=2&c=3 + + + + + + + 使用Get方法获取字符串结果 + + + + + + + + + 使用Post方法获取字符串结果,常规提交 + + + + + + 发送HttpPost请求,使用JSON格式传输数据 + + + + + + + + + + 使用POST请求数据,使用JSON传输数据 + + + 传输对象,转换为JSON传输 + + + + + + + 使用Post方法获取字符串结果 + + + + + + + + + + + + 把响应流转换为文本。 + + 响应流对象 + 编码方式 + 响应文本 + + + + 计算坐标点的距离,直线距离 + + 开始的纬度 + 开始的经度 + 结束的纬度 + 结束的经度 + 距离(公里) + + + + 计算两点之间角度 + + + + + + + + + + 传入经度纬度 + + 经度 + 纬度 + + + + 解析base64信息数据 + + 解析编码格式 + 传入的base64位值 + + + + + 根据经纬度获取地图信息(高德) + + 超时时间默认10秒 + 经纬度字符串 + 失败返回"" + + + + 根据经纬度获取地址,多个 + + 超时时间默认10秒 + 经纬度数组 + 1、获取详细地址2、获取市跟区 + 失败返回"" + + + + 根据经纬度获取地址,一个 + + + + 超时时间默认10秒 + + 失败返回"" + + + + 获取路径规划路线 + + 起点经度 + 起点纬度 + 终点经度 + 终点纬度 + 超时时间默认10秒 + 失败返回"" + + + + 根据起点终点经纬度获取路径规划(步行)(高德) + + 终点经纬度 + 超时时间默认10秒 + 起点经纬度 + 失败返回"" + + + 计算两个经纬度之间的距离 + @param lat1 + @param lng1 + @param lat2 + @param lng2 + @return + + + + 根据起点终点经纬度获取路径规划(驾车)(高德) + + 终点经纬度 + 超时时间默认10秒 + 起点经纬度 + 失败返回"" + + + + + + + + + + + + 路径规划实体 + + + + + 结果状态值,值为0或1 + + + + + 返回状态说明 + + + + + + + + + + 驾车路径规划方案数目 + + + + + 驾车路径规划信息列表 + + + + + 驾车路径规划信息列表 + + + + + 起点坐标 + + + + + 终点坐标 + + + + + 驾车换乘方案 + + + + + 驾车换乘方案 + + + + + 行驶距离 + + + + + 预计行驶时间 + + + + + 导航策略 + + + + + 此导航方案道路收费 + + + + 纬度 X + 经度 Y + + + + 代表纬度 X轴 + + + + + 代表经度 Y轴 d + + + + + 正则帮助类。含大量常用正则表达式。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 判断是否是mac地址 + + mac地址字符串 + + + + + 获取字节数 + str:需要获取的字符串 + + + + + + + + + + + 判断是否字母 + + + + + 判断是否汉字 + + + + + 短信服务 + + + + + 发送短信 + + +86格式 + + + + + + + 字符串帮助类 + + + + + 生成随机字符串,默认32位 + + 随机数长度 + + + + + 生成随机字符串,只包含数字 + + + + + + + 隐藏手机号 + + + + + + + 隐藏身份证号 + + + + + + + 计算时间间隔 + + + + + + + 将对象属性转换为key-value对 + + + + + + + 返回首字母 + + + + 获得字符串首字符字母(大写); + + + + + + + 比较两个时间相差的分钟 + + 开始时间 + 结束时间 + 返回(分钟) + + + + 时间差格式转换 + + 时间差 + 精确度,默认为2 + + + + + 获取时间格式(yyyy-MM-dd HH:mm:ss) + + + + + + + 获取时间格式(yyyy-MM-dd HH:mm:ss) + + + + + + + 得到时间戳 + + + + + + 得到时间戳 + + + + + + 获取某段日期范围内的所有日期 + + 开始日期 + 结束日期 + + + + + 上传单文件 + + + + + + + + + 保存文件 + + + + + + + + + + 保存文件 + + + + + + + + 数据类型转换 + + + + + 转换成Double/Single + + + 小数位数 + + + + + 转换为16进制 + + + 是否小写 + + + + + 16进制转字节数组 + + + + + + + 转换为Base64 + + + + + + + XSS过滤 + + html代码 + 过滤结果 + + + + 路径规划实体 + + + + + 返回状态 + 值为0或1 1:成功;0:失败 + + + + + 返回的状态信息 + status为0时,info返回错误原;否则返回“OK”。详情参阅info状态表 + + + + + 返回结果总数目 + + + + + 路线信息列表 + + + + + 起点坐标 + + + + + 终点坐标 + + + + + 步行方案 + + + + + 起点和终点的步行距离 + 单位:米 + + + + + 步行时间预计 + 单位:秒 + + + + + 返回步行结果列表 + + + + + 每段步行方案 + + + + + 方向 + + + + + 道路名称 + + + + + 此路段距离 + + + + + 此路段预计步行时间 + + + + + 此路段坐标点 + + + + + 后台日志写入服务 + + + + + 任务开始 + + + + + + + 工作线程 + + + + + 用户管理 + + + + + 用户Id + + + + + 权限Id + + + + + 昵称 + + + + + CompanyId + + + + + Account + + + + + SessionKey + + + + + 刷新令牌设置 + + + + + 令牌过期时间(分钟) + + + + + 简单泛型队列 + + + + + + 新增 + + + + + + 取出 + + + + + + + 总数 + + + + + + 清理 + + + + + sql高级代理 + + + + + 阿里云oss文件上传工具类 + + + + + 上传本地文件(走阿里云内网传输) + + + + + + + + 上传一个图片 + + 图片经过base64加密后的结果 + 文件名,例如:Emplyoee/dzzBack.jpg + + + + 上传本地文件 + + + + 返回参数说明 1.本地文件不存在 2.文件oss上已存在 3.上传失败 4.上传成功 + + + + + 上传一个图片 + + 图片字节 + 文件名,例如:Emplyoee/dzzBack.jpg + + + + + 获取鉴权后的URL,URL有效日期默认一小时 + + 文件名,例如:Emplyoee/dzzBack.jpg + + + + + 获取鉴权后的URL + + 文件名,例如:Emplyoee/dzzBack.jpg + URL有效日期,例如:DateTime.Now.AddHours(1) + + + + + 将文件转换成byte[] 数组 + + 文件路径文件名称 + byte[] + + + + 删除文件 + + 文件id + 文件url + + + + 删除文件夹 + + 文件id + 文件url + + + + 判断文件是否存在 + + + + + + + 类型转换 + + + + + + 反射工具 + + + + + 获取字段特性 + + + + + + + + 定时任务 + + + + + 任务名称 + + dilon + + + + 执行间隔时间(单位秒) + + 5 + + + + Cron表达式 + + + + + + 定时器类型 + + + + + 执行次数 + + + + + 请求url + + + + + 请求参数(Post,Put请求用) + + + + + Headers(可以包含如:Authorization授权认证) + 格式:{"Authorization":"userpassword.."} + + + + + 请求类型 + + 2 + + + + 备注 + + + + diff --git a/src/Znyc.Dispatching.Core/coreconfig.Development.json b/src/Znyc.Dispatching.Core/coreconfig.Development.json new file mode 100644 index 0000000..a3676b5 --- /dev/null +++ b/src/Znyc.Dispatching.Core/coreconfig.Development.json @@ -0,0 +1,36 @@ +{ + "SpecificationDocumentSettings": { + "DocumentTitle": "Znyc", + "DocExpansionState": "None", + "GroupOpenApiInfos": [ + { + "Group": "v1", + "Title": "Znyc.Dispatching.Web.Api", + "Description": "", + "Version": "1.0.0" + } + ] + }, + "Cache": { + //测试环境调试配置,非必要请在本地进行开发调试 + "RedisConnectionString": "42.194.147.251:6379,password=vtgA9HXFQQYA9g8Z,defaultDatabase=6" + //"RedisConnectionString": "127.0.0.1:6379" + }, + "SnowId": { + "WorkerId": "1" + }, + "SMSProvider": { + "SecretId": "AKIDGSN2VjJkZ7pIYzcdo0zjDCKCnQpEhXbW", + "SecretKey": "rQDI7fuoUyIEvLT5RWKqkUyGQJwBiU2P", + "SmsSdkAppid": "1400497500", + "Sign": "众能云车", + "Region": "ap-guangzhou", + "TemplateList": [ + { + "ChangePassWordTemplateId": "953233", + "RegisterTemplateId": "953232", + "AddEmployeeTemplateId": "970368" + } + ] + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/coreconfig.Production.json b/src/Znyc.Dispatching.Core/coreconfig.Production.json new file mode 100644 index 0000000..73a0341 --- /dev/null +++ b/src/Znyc.Dispatching.Core/coreconfig.Production.json @@ -0,0 +1,35 @@ +{ + "SpecificationDocumentSettings": { + "DocumentTitle": "Znyc", + "DocExpansionState": "None", + "GroupOpenApiInfos": [ + { + "Group": "v1", + "Title": "Znyc.Dispatching.Web.Api", + "Description": "", + "Version": "1.0.0" + } + ] + }, + "Cache": { + "CacheType": "RedisCache", + "RedisConnectionString": "172.16.0.17:6379,defaultDatabase=6" + }, + "SnowId": { + "WorkerId": "1" + }, + "SMSProvider": { + "SecretId": "AKIDGSN2VjJkZ7pIYzcdo0zjDCKCnQpEhXbW", + "SecretKey": "rQDI7fuoUyIEvLT5RWKqkUyGQJwBiU2P", + "SmsSdkAppid": "1400497500", + "Sign": "众能云车", + "Region": "ap-guangzhou", + "TemplateList": [ + { + "ChangePassWordTemplateId": "953233", + "RegisterTemplateId": "953232", + "AddEmployeeTemplateId": "970368" + } + ] + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Core/coreconfig.Staging.json b/src/Znyc.Dispatching.Core/coreconfig.Staging.json new file mode 100644 index 0000000..bd839a3 --- /dev/null +++ b/src/Znyc.Dispatching.Core/coreconfig.Staging.json @@ -0,0 +1,34 @@ +{ + "SpecificationDocumentSettings": { + "DocumentTitle": "Znyc", + "DocExpansionState": "None", + "GroupOpenApiInfos": [ + { + "Group": "v1", + "Title": "Znyc.Dispatching.Web.Api", + "Description": "", + "Version": "1.0.0" + } + ] + }, + "Cache": { + "RedisConnectionString": "10.0.8.5:6379,password=vtgA9HXFQQYA9g8Z,defaultDatabase=6" + }, + "SnowId": { + "WorkerId": "1" + }, + "SMSProvider": { + "SecretId": "AKIDGSN2VjJkZ7pIYzcdo0zjDCKCnQpEhXbW", + "SecretKey": "rQDI7fuoUyIEvLT5RWKqkUyGQJwBiU2P", + "SmsSdkAppid": "1400497500", + "Sign": "众能云车", + "Region": "ap-guangzhou", + "TemplateList": [ + { + "ChangePassWordTemplateId": "953233", + "RegisterTemplateId": "953232", + "AddEmployeeTemplateId": "970368" + } + ] + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Database.Migrations/MSBuild_Logs/MSBuild_pid-18752_4d6113493f7a4e73b20c145787e2b4ff.failure.txt b/src/Znyc.Dispatching.Database.Migrations/MSBuild_Logs/MSBuild_pid-18752_4d6113493f7a4e73b20c145787e2b4ff.failure.txt new file mode 100644 index 0000000..2e2d9e0 --- /dev/null +++ b/src/Znyc.Dispatching.Database.Migrations/MSBuild_Logs/MSBuild_pid-18752_4d6113493f7a4e73b20c145787e2b4ff.failure.txt @@ -0,0 +1,8 @@ +UNHANDLED EXCEPTIONS FROM PROCESS 18752: +===================== +2021/9/9 11:42:52 +System.IO.IOException: 管道已中断。 + 在 System.IO.Pipes.NamedPipeServerStream.CheckConnectOperationsServer() + 在 System.IO.Pipes.NamedPipeServerStream.BeginWaitForConnection(AsyncCallback callback, Object state) + 在 Microsoft.Build.BackEnd.NodeEndpointOutOfProcBase.PacketPumpProc() +=================== diff --git a/src/Znyc.Dispatching.Database.Migrations/Znyc.Dispatching.Database.Migrations.csproj b/src/Znyc.Dispatching.Database.Migrations/Znyc.Dispatching.Database.Migrations.csproj new file mode 100644 index 0000000..f9f7fe6 --- /dev/null +++ b/src/Znyc.Dispatching.Database.Migrations/Znyc.Dispatching.Database.Migrations.csproj @@ -0,0 +1,10 @@ + + + + net6.0 + + + + + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.EntityFramework.Core/DbContexts/DefaultDbContext.cs b/src/Znyc.Dispatching.EntityFramework.Core/DbContexts/DefaultDbContext.cs new file mode 100644 index 0000000..2bcfd2a --- /dev/null +++ b/src/Znyc.Dispatching.EntityFramework.Core/DbContexts/DefaultDbContext.cs @@ -0,0 +1,177 @@ +using Furion; +using Furion.DatabaseAccessor; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +using System.Linq; +using System.Linq.Expressions; +using Yitter.IdGenerator; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Entitys; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.EntityFramework.Core +{ + [AppDbContext("DefaultConnection", DbProvider.MySql)] + public class DefaultDbContext : AppDbContext, IModelBuilderFilter + { + + public DefaultDbContext(DbContextOptions options) : + base(options) + { + //log + + // 启用实体数据更改监听 + // EnabledEntityChangedListener = true; + + // 忽略空值更新 + InsertOrUpdateIgnoreNullValues = true; + } + + /// + /// 配置假删除过滤器 + /// + /// + /// + /// + /// + public void OnCreating(ModelBuilder modelBuilder, EntityTypeBuilder entityBuilder, DbContext dbContext, + Type dbContextLocator) + { + // 配置假删除过滤器 + LambdaExpression expression = FakeDeleteQueryFilterExpression(entityBuilder, dbContext); + if (expression != null) + { + entityBuilder.HasQueryFilter(expression); + } + } + + /// + /// 重写保存之前事件 + /// + /// + /// + protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult result) + { + // 获取当前事件对应上下文 + var dbContext = eventData.Context; + + // 强制重新检查一边实体更改信息 + dbContext.ChangeTracker.DetectChanges(); + + //// 获取所有更改,删除,新增的实体,但排除审计实体(避免死循环) + var entities = dbContext.ChangeTracker.Entries() + .Where(u => u.Entity.GetType() != typeof(LogAudit) && + (u.State == EntityState.Modified || u.State == EntityState.Deleted || + u.State == EntityState.Added)) + .ToList(); + + string userId = App.User.IsNull() ? "0" : App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value; + foreach (Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry entity in entities) + { + if (entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase))) + { + DEntityBase obj = entity.Entity as DEntityBase; + if (entity.State == EntityState.Added) + { + obj.Id = obj.Id == 0 ? YitIdHelper.NextId() : obj.Id; + obj.CreatedTime = DateTime.Now; + if (!string.IsNullOrEmpty(userId)) + { + obj.CreatedUserId = long.Parse(userId); + obj.CreatedTime = DateTime.Now; + ; + } + } + else if (entity.State == EntityState.Modified) + { + entity.Property(nameof(DEntityBase.CreatedUserId)).IsModified = false; + entity.Property(nameof(DEntityBase.CreatedTime)).IsModified = false; + obj.ModifiedTime = DateTime.Now; + obj.ModifiedUserId = userId.IsNotNull() ? long.Parse(userId) : 0; + } + } + } + + #region 数据库审计 + + //// 获取所有已更改的实体 + //foreach (var entity in entities) + //{ + // // 获取实体类型 + // var entityType = entity.Entity.GetType(); + + // // 获取所有实体有效属性,排除 [NotMapper] 属性 + // var props = entity.OriginalValues.Properties; + + // // 获取实体当前(现在)的值 + // var currentValues = entity.CurrentValues; + + // // 获取数据库中实体的值 + // var databaseValues = entity.GetDatabaseValues(); + + // // 遍历所有属性 + // foreach (var prop in props) + // { + // // 获取属性名 + // var propName = prop.Name; + + // // 获取现在的实体值 + // var newValue = currentValues[propName]; + + // object oldValue = null; + // // 如果是新增数据,则 databaseValues 为空,所以需要判断一下 + // if (databaseValues != null) + // { + // oldValue = databaseValues[propName]; + // } + + // _logger.LogInformation(JsonConvert.SerializeObject(new LogAudit + // { + // TableName = entityType.Name, // 表名 + // ColumnName = propName, // 更新的列 + // NewValue = newValue.ToString(), // 新值 + // OldValue = oldValue.ToString(), // 旧值 + // CreatedTime = DateTime.Now, // 操作时间 + // UserId = ConvertHelper.ConvertTo(userId), // 操作人 + // Operate = entity.State.ToString() // 操作方式:新增、更新、删除 + // })); + + // } + //} + + #endregion 数据库审计 + } + + /// + /// 构建假删除过滤器 + /// + /// + /// + /// + /// + /// + protected static LambdaExpression FakeDeleteQueryFilterExpression(EntityTypeBuilder entityBuilder, + DbContext dbContext, string isDeletedKey = null, object filterValue = null) + { + isDeletedKey ??= "IsDeleted"; + Microsoft.EntityFrameworkCore.Metadata.IMutableEntityType metadata = entityBuilder.Metadata; + Expression finialExpression = Expression.Constant(true); + ParameterExpression parameterExpression = Expression.Parameter(metadata.ClrType, "u"); + // 假删除过滤器 + if (metadata.FindProperty(isDeletedKey) != null) + { + ConstantExpression constantExpression = Expression.Constant(isDeletedKey); + ConstantExpression right = Expression.Constant(filterValue ?? false); + BinaryExpression fakeDeleteQueryExpression = Expression.Equal(Expression.Call(typeof(EF), "Property", new Type[1] + { + typeof(bool) + }, parameterExpression, constantExpression), right); + finialExpression = Expression.AndAlso(finialExpression, fakeDeleteQueryExpression); + } + + return Expression.Lambda(finialExpression, parameterExpression); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.EntityFramework.Core/EntityFrameworkStartup.cs b/src/Znyc.Dispatching.EntityFramework.Core/EntityFrameworkStartup.cs new file mode 100644 index 0000000..009b42c --- /dev/null +++ b/src/Znyc.Dispatching.EntityFramework.Core/EntityFrameworkStartup.cs @@ -0,0 +1,24 @@ +using Furion; +using Furion.DatabaseAccessor; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Znyc.Dispatching.EntityFramework.Core +{ + [AppStartup(90)] + public class EntityFrameworkStartup : AppStartup + { + public void ConfigureServices(IServiceCollection services) + { + services.AddDatabaseAccessor(options => + { + //默认数据 + options.AddDb($"{DbProvider.MySql}", + opt => + { + opt.UseBatchEF_MySQLPomelo(); + }); + }); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.EntityFramework.Core/Znyc.Dispatching.EntityFramework.Core.csproj b/src/Znyc.Dispatching.EntityFramework.Core/Znyc.Dispatching.EntityFramework.Core.csproj new file mode 100644 index 0000000..45a0cdb --- /dev/null +++ b/src/Znyc.Dispatching.EntityFramework.Core/Znyc.Dispatching.EntityFramework.Core.csproj @@ -0,0 +1,36 @@ + + + + net6.0 + + + + + + + + + + + + Always + + + Always + + + Always + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.EntityFramework.Core/dbsettings.Development.json b/src/Znyc.Dispatching.EntityFramework.Core/dbsettings.Development.json new file mode 100644 index 0000000..1707909 --- /dev/null +++ b/src/Znyc.Dispatching.EntityFramework.Core/dbsettings.Development.json @@ -0,0 +1,7 @@ +{ + "ConnectionStrings": { + //ԻãDZҪڱؽп + "DefaultConnection": "Server=42.194.147.251;Port=43306;Database=znyc_dispatching;Uid=guest;Pwd=4Y2e2WtekfDYWfT8;Charset=utf8mb4;AllowLoadLocalInfile=true" + //"DefaultConnection": "Server=127.0.0.1;Port=3306;Database=znyc_dispatching;Uid=root;Pwd=123456;Charset=utf8mb4" + } +} diff --git a/src/Znyc.Dispatching.EntityFramework.Core/dbsettings.Production.json b/src/Znyc.Dispatching.EntityFramework.Core/dbsettings.Production.json new file mode 100644 index 0000000..829eb6b --- /dev/null +++ b/src/Znyc.Dispatching.EntityFramework.Core/dbsettings.Production.json @@ -0,0 +1,6 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "Server=172.16.0.6; Port=3306; Database=znyc_dispatching; Uid=znyc; Pwd=UhcAoRR5A3hnt^%U; Charset=utf8mb4" + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.EntityFramework.Core/dbsettings.Staging.json b/src/Znyc.Dispatching.EntityFramework.Core/dbsettings.Staging.json new file mode 100644 index 0000000..c614f41 --- /dev/null +++ b/src/Znyc.Dispatching.EntityFramework.Core/dbsettings.Staging.json @@ -0,0 +1,5 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "Server=10.0.8.5;Port=43306;Database=znyc_dispatching;Uid=guest;Pwd=4Y2e2WtekfDYWfT8; Charset=utf8mb4" + } +} diff --git a/src/Znyc.Dispatching.Evenbus/EventBusSubscriptions/InMemoryEventBusSubscriptionsManager.cs b/src/Znyc.Dispatching.Evenbus/EventBusSubscriptions/InMemoryEventBusSubscriptionsManager.cs new file mode 100644 index 0000000..5a0b709 --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/EventBusSubscriptions/InMemoryEventBusSubscriptionsManager.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Znyc.Dispatching.Evenbus +{ + /// + /// 基于内存 + /// 事件总线订阅管理器 + /// 单例模式 + /// + public class InMemoryEventBusSubscriptionsManager : IEventBusSubscriptionsManager + { + private readonly List _eventTypes; + private readonly Dictionary> _handlers; + + public InMemoryEventBusSubscriptionsManager() + { + _handlers = new Dictionary>(); + _eventTypes = new List(); + } + + public event EventHandler OnEventRemoved; + + public bool IsEmpty => !_handlers.Keys.Any(); + + public void Clear() + { + _handlers.Clear(); + } + + /// + /// 添加动态订阅 + /// + /// 约束:动态事件处理器接口 + /// + public void AddDynamicSubscription(string eventName) + where TH : IDynamicIntegrationEventHandler + { + DoAddSubscription(typeof(TH), eventName, true); + } + + /// + /// 添加订阅 + /// + /// 约束:事件 + /// 约束:事件处理器接口<事件> + public void AddSubscription() + where T : IntegrationEvent + where TH : IIntegrationEventHandler + { + var eventName = GetEventKey(); + + DoAddSubscription(typeof(TH), eventName, false); + + if (!_eventTypes.Contains(typeof(T))) _eventTypes.Add(typeof(T)); + } + + /// + /// 移除动态订阅 + /// + /// + /// + public void RemoveDynamicSubscription(string eventName) + where TH : IDynamicIntegrationEventHandler + { + var handlerToRemove = FindDynamicSubscriptionToRemove(eventName); + DoRemoveHandler(eventName, handlerToRemove); + } + + public void RemoveSubscription() + where TH : IIntegrationEventHandler + where T : IntegrationEvent + { + var handlerToRemove = FindSubscriptionToRemove(); + var eventName = GetEventKey(); + DoRemoveHandler(eventName, handlerToRemove); + } + + public IEnumerable GetHandlersForEvent() where T : IntegrationEvent + { + var key = GetEventKey(); + return GetHandlersForEvent(key); + } + + public IEnumerable GetHandlersForEvent(string eventName) + { + return _handlers[eventName]; + } + + public bool HasSubscriptionsForEvent() where T : IntegrationEvent + { + var key = GetEventKey(); + return HasSubscriptionsForEvent(key); + } + + public bool HasSubscriptionsForEvent(string eventName) + { + return _handlers.ContainsKey(eventName); + } + + public Type GetEventTypeByName(string eventName) + { + return _eventTypes.SingleOrDefault(t => t.Name == eventName); + } + + public string GetEventKey() + { + return typeof(T).Name; + } + + private void DoAddSubscription(Type handlerType, string eventName, bool isDynamic) + { + if (!HasSubscriptionsForEvent(eventName)) _handlers.Add(eventName, new List()); + + if (_handlers[eventName].Any(s => s.HandlerType == handlerType)) + throw new ArgumentException( + $"Handler Type {handlerType.Name} already registered for '{eventName}'", nameof(handlerType)); + + if (isDynamic) + _handlers[eventName].Add(SubscriptionInfo.Dynamic(handlerType)); + else + _handlers[eventName].Add(SubscriptionInfo.Typed(handlerType)); + } + + private void DoRemoveHandler(string eventName, SubscriptionInfo subsToRemove) + { + if (subsToRemove != null) + { + _handlers[eventName].Remove(subsToRemove); + if (!_handlers[eventName].Any()) + { + _handlers.Remove(eventName); + var eventType = _eventTypes.SingleOrDefault(e => e.Name == eventName); + if (eventType != null) _eventTypes.Remove(eventType); + RaiseOnEventRemoved(eventName); + } + } + } + + private void RaiseOnEventRemoved(string eventName) + { + var handler = OnEventRemoved; + handler?.Invoke(this, eventName); + } + + private SubscriptionInfo FindDynamicSubscriptionToRemove(string eventName) + where TH : IDynamicIntegrationEventHandler + { + return DoFindSubscriptionToRemove(eventName, typeof(TH)); + } + + /// + /// 查询订阅并移除 + /// + /// + /// + /// + private SubscriptionInfo FindSubscriptionToRemove() + where T : IntegrationEvent + where TH : IIntegrationEventHandler + { + var eventName = GetEventKey(); + return DoFindSubscriptionToRemove(eventName, typeof(TH)); + } + + private SubscriptionInfo DoFindSubscriptionToRemove(string eventName, Type handlerType) + { + if (!HasSubscriptionsForEvent(eventName)) return null; + + return _handlers[eventName].SingleOrDefault(s => s.HandlerType == handlerType); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/EventBusSubscriptions/SubscriptionInfo.cs b/src/Znyc.Dispatching.Evenbus/EventBusSubscriptions/SubscriptionInfo.cs new file mode 100644 index 0000000..b059ac8 --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/EventBusSubscriptions/SubscriptionInfo.cs @@ -0,0 +1,29 @@ +using System; + +namespace Znyc.Dispatching.Evenbus +{ + /// + /// 订阅信息模型 + /// + public class SubscriptionInfo + { + private SubscriptionInfo(bool isDynamic, Type handlerType) + { + IsDynamic = isDynamic; + HandlerType = handlerType; + } + + public bool IsDynamic { get; } + public Type HandlerType { get; } + + public static SubscriptionInfo Dynamic(Type handlerType) + { + return new(true, handlerType); + } + + public static SubscriptionInfo Typed(Type handlerType) + { + return new(false, handlerType); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/Eventbus/IDynamicIntegrationEventHandler.cs b/src/Znyc.Dispatching.Evenbus/Eventbus/IDynamicIntegrationEventHandler.cs new file mode 100644 index 0000000..aacf97a --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/Eventbus/IDynamicIntegrationEventHandler.cs @@ -0,0 +1,13 @@ +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Evenbus +{ + /// + /// 动态集成事件处理程序 + /// 接口 + /// + public interface IDynamicIntegrationEventHandler + { + Task Handle(dynamic eventData); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/Eventbus/IEventBus.cs b/src/Znyc.Dispatching.Evenbus/Eventbus/IEventBus.cs new file mode 100644 index 0000000..19642ae --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/Eventbus/IEventBus.cs @@ -0,0 +1,49 @@ +namespace Znyc.Dispatching.Evenbus +{ + /// + /// 事件总线 + /// 接口 + /// + public interface IEventBus + { + /// + /// 发布 + /// + /// 事件模型 + void Publish(IntegrationEvent @event); + + /// + /// 订阅 + /// + /// 约束:事件模型 + /// 约束:事件处理器<事件模型> + void Subscribe() + where T : IntegrationEvent + where TH : IIntegrationEventHandler; + + /// + /// 取消订阅 + /// + /// + /// + void Unsubscribe() + where TH : IIntegrationEventHandler + where T : IntegrationEvent; + + /// + /// 动态订阅 + /// + /// 约束:事件处理器 + /// + void SubscribeDynamic(string eventName) + where TH : IDynamicIntegrationEventHandler; + + /// + /// 动态取消订阅 + /// + /// + /// + void UnsubscribeDynamic(string eventName) + where TH : IDynamicIntegrationEventHandler; + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/Eventbus/IEventBusSubscriptionsManager.cs b/src/Znyc.Dispatching.Evenbus/Eventbus/IEventBusSubscriptionsManager.cs new file mode 100644 index 0000000..7207d64 --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/Eventbus/IEventBusSubscriptionsManager.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; + +namespace Znyc.Dispatching.Evenbus +{ + /// + /// 事件总线订阅管理器 + /// 接口 + /// + public interface IEventBusSubscriptionsManager + { + bool IsEmpty { get; } + + event EventHandler OnEventRemoved; + + void AddDynamicSubscription(string eventName) + where TH : IDynamicIntegrationEventHandler; + + void AddSubscription() + where T : IntegrationEvent + where TH : IIntegrationEventHandler; + + void RemoveSubscription() + where TH : IIntegrationEventHandler + where T : IntegrationEvent; + + void RemoveDynamicSubscription(string eventName) + where TH : IDynamicIntegrationEventHandler; + + bool HasSubscriptionsForEvent() where T : IntegrationEvent; + + bool HasSubscriptionsForEvent(string eventName); + + Type GetEventTypeByName(string eventName); + + void Clear(); + + IEnumerable GetHandlersForEvent() where T : IntegrationEvent; + + IEnumerable GetHandlersForEvent(string eventName); + + string GetEventKey(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/Eventbus/IIntegrationEventHandler.cs b/src/Znyc.Dispatching.Evenbus/Eventbus/IIntegrationEventHandler.cs new file mode 100644 index 0000000..e75e331 --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/Eventbus/IIntegrationEventHandler.cs @@ -0,0 +1,23 @@ +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Evenbus +{ + /// + /// 集成事件处理程序 + /// 泛型接口 + /// + /// + public interface IIntegrationEventHandler : IIntegrationEventHandler + where TIntegrationEvent : IntegrationEvent + { + Task Handle(TIntegrationEvent @event); + } + + /// + /// 集成事件处理程序 + /// 基 接口 + /// + public interface IIntegrationEventHandler + { + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/Eventbus/IntegrationEvent.cs b/src/Znyc.Dispatching.Evenbus/Eventbus/IntegrationEvent.cs new file mode 100644 index 0000000..7be3d83 --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/Eventbus/IntegrationEvent.cs @@ -0,0 +1,29 @@ +using System; +using Newtonsoft.Json; + +namespace Znyc.Dispatching.Evenbus +{ + /// + /// 事件模型 + /// 基类 + /// + public class IntegrationEvent + { + public IntegrationEvent() + { + Id = Guid.NewGuid(); + CreationDate = DateTime.UtcNow; + } + + [JsonConstructor] + public IntegrationEvent(Guid id, DateTime createDate) + { + Id = id; + CreationDate = createDate; + } + + [JsonProperty] public Guid Id { get; private set; } + + [JsonProperty] public DateTime CreationDate { get; private set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/RabbitMQPersistent/EventBusRabbitMQ.cs b/src/Znyc.Dispatching.Evenbus/RabbitMQPersistent/EventBusRabbitMQ.cs new file mode 100644 index 0000000..63c9a67 --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/RabbitMQPersistent/EventBusRabbitMQ.cs @@ -0,0 +1,336 @@ +using System; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; +using Autofac; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Polly; +using RabbitMQ.Client; +using RabbitMQ.Client.Events; +using RabbitMQ.Client.Exceptions; +using Znyc.Dispatching.Common.Extensions; + +namespace Znyc.Dispatching.Evenbus +{ + /// + /// 基于RabbitMQ的事件总线 + /// + public class EventBusRabbitMQ : IEventBus, IDisposable + { + private const string BROKER_NAME = "blogcore_event_bus"; + private readonly ILifetimeScope _autofac; + private readonly ILogger _logger; + + private readonly IRabbitMQPersistentConnection _persistentConnection; + private readonly int _retryCount; + private readonly IEventBusSubscriptionsManager _subsManager; + private readonly string AUTOFAC_SCOPE_NAME = "dispatching_event_bus"; + + private IModel _consumerChannel; + private string _queueName; + + /// + /// RabbitMQ事件总线 + /// + /// RabbitMQ持久连接 + /// 日志 + /// autofac容器 + /// 事件总线订阅管理器 + /// 队列名称 + /// 重试次数 + public EventBusRabbitMQ(IRabbitMQPersistentConnection persistentConnection, ILogger logger, + ILifetimeScope autofac, + IEventBusSubscriptionsManager subsManager, + string? queueName = null, + int retryCount = 5) + { + _persistentConnection = + persistentConnection ?? throw new ArgumentNullException(nameof(persistentConnection)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager(); + _queueName = queueName; + _consumerChannel = CreateConsumerChannel(); + _retryCount = retryCount; + _autofac = autofac; + _subsManager.OnEventRemoved += SubsManager_OnEventRemoved; + } + + public void Dispose() + { + if (_consumerChannel != null) _consumerChannel.Dispose(); + + _subsManager.Clear(); + } + + /// + /// 发布 + /// + /// 事件模型 + public void Publish(IntegrationEvent @event) + { + if (!_persistentConnection.IsConnected) _persistentConnection.TryConnect(); + + var policy = Policy.Handle() + .Or() + .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), + (ex, time) => + { + _logger.LogWarning(ex, + "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", @event.Id, + $"{time.TotalSeconds:n1}", ex.Message); + }); + + var eventName = @event.GetType().Name; + + _logger.LogTrace("Creating RabbitMQ channel to publish event: {EventId} ({EventName})", @event.Id, + eventName); + + using (var channel = _persistentConnection.CreateModel()) + { + _logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id); + + channel.ExchangeDeclare(BROKER_NAME, "direct"); + + var message = JsonConvert.SerializeObject(@event); + var body = Encoding.UTF8.GetBytes(message); + + policy.Execute(() => + { + var properties = channel.CreateBasicProperties(); + properties.DeliveryMode = 2; // persistent + + _logger.LogTrace("Publishing event to RabbitMQ: {EventId}", @event.Id); + + channel.BasicPublish( + BROKER_NAME, + eventName, + true, + properties, + body); + }); + } + } + + /// + /// 订阅 + /// 动态 + /// + /// 事件处理器 + /// 事件名 + public void SubscribeDynamic(string eventName) + where TH : IDynamicIntegrationEventHandler + { + _logger.LogInformation("Subscribing to dynamic event {EventName} with {EventHandler}", eventName, + typeof(TH).GetGenericTypeName()); + + DoInternalSubscription(eventName); + _subsManager.AddDynamicSubscription(eventName); + StartBasicConsume(); + } + + /// + /// 订阅 + /// + /// 约束:事件模型 + /// 约束:事件处理器<事件模型> + public void Subscribe() + where T : IntegrationEvent + where TH : IIntegrationEventHandler + { + var eventName = _subsManager.GetEventKey(); + DoInternalSubscription(eventName); + + _logger.LogInformation("Subscribing to event {EventName} with {EventHandler}", eventName, + typeof(TH).GetGenericTypeName()); + + Console.WriteLine($"Subscribing to event {eventName} with {typeof(TH).GetGenericTypeName()}"); + + _subsManager.AddSubscription(); + StartBasicConsume(); + } + + /// + /// 取消订阅 + /// + /// + /// + public void Unsubscribe() + where T : IntegrationEvent + where TH : IIntegrationEventHandler + { + var eventName = _subsManager.GetEventKey(); + + _logger.LogInformation("Unsubscribing from event {EventName}", eventName); + + _subsManager.RemoveSubscription(); + } + + public void UnsubscribeDynamic(string eventName) + where TH : IDynamicIntegrationEventHandler + { + _subsManager.RemoveDynamicSubscription(eventName); + } + + /// + /// 订阅管理器事件 + /// + /// + /// + private void SubsManager_OnEventRemoved(object sender, string eventName) + { + if (!_persistentConnection.IsConnected) _persistentConnection.TryConnect(); + + using (var channel = _persistentConnection.CreateModel()) + { + channel.QueueUnbind(_queueName, + BROKER_NAME, + eventName); + + if (_subsManager.IsEmpty) + { + _queueName = string.Empty; + _consumerChannel.Close(); + } + } + } + + private void DoInternalSubscription(string eventName) + { + var containsKey = _subsManager.HasSubscriptionsForEvent(eventName); + if (!containsKey) + { + if (!_persistentConnection.IsConnected) _persistentConnection.TryConnect(); + + using (var channel = _persistentConnection.CreateModel()) + { + channel.QueueBind(_queueName, + BROKER_NAME, + eventName); + } + } + } + + /// + /// 开始基本消费 + /// + private void StartBasicConsume() + { + _logger.LogTrace("Starting RabbitMQ basic consume"); + + if (_consumerChannel != null) + { + var consumer = new AsyncEventingBasicConsumer(_consumerChannel); + + consumer.Received += Consumer_Received; + + _consumerChannel.BasicConsume( + _queueName, + false, + consumer); + } + else + { + _logger.LogError("StartBasicConsume can't call on _consumerChannel == null"); + } + } + + /// + /// 消费者接受到 + /// + /// + /// + /// + private async Task Consumer_Received(object sender, BasicDeliverEventArgs eventArgs) + { + var eventName = eventArgs.RoutingKey; + var message = Encoding.UTF8.GetString(eventArgs.Body.Span); + + try + { + if (message.ToLowerInvariant().Contains("throw-fake-exception")) + throw new InvalidOperationException($"Fake exception requested: \"{message}\""); + + await ProcessEvent(eventName, message); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "----- ERROR Processing message \"{Message}\"", message); + } + + // Even on exception we take the message off the queue. + // in a REAL WORLD app this should be handled with a Dead Letter Exchange (DLX). + // For more information see: https://www.rabbitmq.com/dlx.html + _consumerChannel.BasicAck(eventArgs.DeliveryTag, false); + } + + /// + /// 创造消费通道 + /// + /// + private IModel CreateConsumerChannel() + { + if (!_persistentConnection.IsConnected) _persistentConnection.TryConnect(); + + _logger.LogTrace("Creating RabbitMQ consumer channel"); + + var channel = _persistentConnection.CreateModel(); + + channel.ExchangeDeclare(BROKER_NAME, + "direct"); + + channel.QueueDeclare(_queueName, + true, + false, + false, + null); + + channel.CallbackException += (sender, ea) => + { + _logger.LogWarning(ea.Exception, "Recreating RabbitMQ consumer channel"); + + _consumerChannel.Dispose(); + _consumerChannel = CreateConsumerChannel(); + StartBasicConsume(); + }; + + return channel; + } + + private async Task ProcessEvent(string eventName, string message) + { + _logger.LogTrace("Processing RabbitMQ event: {EventName}", eventName); + + if (_subsManager.HasSubscriptionsForEvent(eventName)) + using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME)) + { + var subscriptions = _subsManager.GetHandlersForEvent(eventName); + foreach (var subscription in subscriptions) + if (subscription.IsDynamic) + { + var handler = + scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler; + if (handler == null) continue; + dynamic eventData = JObject.Parse(message); + + await Task.Yield(); + await handler.Handle(eventData); + } + else + { + var handler = scope.ResolveOptional(subscription.HandlerType); + if (handler == null) continue; + var eventType = _subsManager.GetEventTypeByName(eventName); + var integrationEvent = JsonConvert.DeserializeObject(message, eventType); + var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); + + await Task.Yield(); + await (Task) concreteType.GetMethod("Handle").Invoke(handler, new[] {integrationEvent}); + } + } + else + _logger.LogWarning("No subscription for RabbitMQ event: {EventName}", eventName); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/RabbitMQPersistent/IRabbitMQPersistentConnection.cs b/src/Znyc.Dispatching.Evenbus/RabbitMQPersistent/IRabbitMQPersistentConnection.cs new file mode 100644 index 0000000..2d948ef --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/RabbitMQPersistent/IRabbitMQPersistentConnection.cs @@ -0,0 +1,19 @@ +using System; +using RabbitMQ.Client; + +namespace Znyc.Dispatching.Evenbus +{ + /// + /// RabbitMQ持久连接 + /// 接口 + /// + public interface IRabbitMQPersistentConnection + : IDisposable + { + bool IsConnected { get; } + + bool TryConnect(); + + IModel CreateModel(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/RabbitMQPersistent/RabbitMQPersistentConnection.cs b/src/Znyc.Dispatching.Evenbus/RabbitMQPersistent/RabbitMQPersistentConnection.cs new file mode 100644 index 0000000..b7ba470 --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/RabbitMQPersistent/RabbitMQPersistentConnection.cs @@ -0,0 +1,161 @@ +using System; +using System.IO; +using System.Net.Sockets; +using Microsoft.Extensions.Logging; +using Polly; +using RabbitMQ.Client; +using RabbitMQ.Client.Events; +using RabbitMQ.Client.Exceptions; + +namespace Znyc.Dispatching.Evenbus +{ + /// + /// RabbitMQ持久连接 + /// + public class RabbitMQPersistentConnection + : IRabbitMQPersistentConnection + { + private readonly IConnectionFactory _connectionFactory; + private readonly ILogger _logger; + private readonly int _retryCount; + private IConnection _connection; + private bool _disposed; + + private readonly object sync_root = new(); + + public RabbitMQPersistentConnection(IConnectionFactory connectionFactory, + ILogger logger, + int retryCount = 5) + { + _connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _retryCount = retryCount; + } + + /// + /// 是否已连接 + /// + public bool IsConnected => _connection != null && _connection.IsOpen && !_disposed; + + /// + /// 创建Model + /// + /// + public IModel CreateModel() + { + if (!IsConnected) + throw new InvalidOperationException("No RabbitMQ connections are available to perform this action"); + + return _connection.CreateModel(); + } + + /// + /// 释放 + /// + public void Dispose() + { + if (_disposed) return; + + _disposed = true; + + try + { + _connection.Dispose(); + } + catch (IOException ex) + { + _logger.LogCritical(ex.ToString()); + } + } + + /// + /// 连接 + /// + /// + public bool TryConnect() + { + _logger.LogInformation("RabbitMQ Client is trying to connect"); + + lock (sync_root) + { + var policy = Policy.Handle() + .Or() + .WaitAndRetry(_retryCount, + retryAttempt => + TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), + (ex, time) => + { + _logger.LogWarning(ex, + "RabbitMQ Client could not connect after {TimeOut}s ({ExceptionMessage})", + $"{time.TotalSeconds:n1}", ex.Message); + } + ); + + policy.Execute(() => + { + _connection = _connectionFactory + .CreateConnection(); + }); + + if (IsConnected) + { + _connection.ConnectionShutdown += OnConnectionShutdown; + _connection.CallbackException += OnCallbackException; + _connection.ConnectionBlocked += OnConnectionBlocked; + + _logger.LogInformation( + "RabbitMQ Client acquired a persistent connection to '{HostName}' and is subscribed to failure events", + _connection.Endpoint.HostName); + + return true; + } + + _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened"); + + return false; + } + } + + /// + /// 连接被阻断 + /// + /// + /// + private void OnConnectionBlocked(object sender, ConnectionBlockedEventArgs e) + { + if (_disposed) return; + + _logger.LogWarning("A RabbitMQ connection is shutdown. Trying to re-connect..."); + + TryConnect(); + } + + /// + /// 连接出现异常 + /// + /// + /// + private void OnCallbackException(object sender, CallbackExceptionEventArgs e) + { + if (_disposed) return; + + _logger.LogWarning("A RabbitMQ connection throw exception. Trying to re-connect..."); + + TryConnect(); + } + + /// + /// 连接被关闭 + /// + /// + /// + private void OnConnectionShutdown(object sender, ShutdownEventArgs reason) + { + if (_disposed) return; + + _logger.LogWarning("A RabbitMQ connection is on shutdown. Trying to re-connect..."); + + TryConnect(); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Evenbus/Znyc.Dispatching.Evenbus.csproj b/src/Znyc.Dispatching.Evenbus/Znyc.Dispatching.Evenbus.csproj new file mode 100644 index 0000000..39a3245 --- /dev/null +++ b/src/Znyc.Dispatching.Evenbus/Znyc.Dispatching.Evenbus.csproj @@ -0,0 +1,21 @@ + + + + net5.0 + enable + + + + + + + + + + + + + + + + diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Collection/GpsCarAccDuration.cs b/src/Znyc.Dispatching.MongoDb.Repository/Collection/GpsCarAccDuration.cs new file mode 100644 index 0000000..167a414 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Collection/GpsCarAccDuration.cs @@ -0,0 +1,58 @@ +using Pursue.Extension.MongoDB; +using System; + +namespace Znyc.Dispatching.MongoDb.Repository.Collection +{ + public class GpsCarAccDuration : MongoEntityPrimaryKey + { + /// + /// 所属车辆 + /// + public long VehicleId { get; set; } + + /// + /// 所属公司 + /// + public long CompanyId { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// ACC状态 + /// + public int AccState { get; set; } + + /// + /// ACC持续时长 + /// + public string AccDurationTime { get; set; } + + /// + /// 开始时间 + /// + public DateTime TimeBegin { get; set; } + + /// + /// 结束时间 + /// + public DateTime TimeEnd { get; set; } + + /// + /// 更新时间 + /// + public DateTime ModifiedTime { get; set; } + + /// + /// 创建时间 + /// + public DateTime CreatedTime { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Collection/GpsRealTime.cs b/src/Znyc.Dispatching.MongoDb.Repository/Collection/GpsRealTime.cs new file mode 100644 index 0000000..f545c23 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Collection/GpsRealTime.cs @@ -0,0 +1,149 @@ +using Pursue.Extension.MongoDB; +using System; + +namespace Znyc.Dispatching.MongoDb.Repository.Collection +{ + public class GpsRealTime : MongoEntityPrimaryKey + { + + private string _accDurationTime; + + /// + /// 车辆ID + /// + public long VehicleId { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// 司机 + /// + public long VehicleDriver { get; set; } + + /// + /// 司机联系电话 + /// + public string DriverPhone { get; set; } + + /// + /// 状态 + /// + public int Status { get; set; } + + /// + /// Gps状态 + /// + public int GpsState { get; set; } + + /// + /// Gps数据产生时间 + /// + public DateTime GpsTime { get; set; } + + /// + /// Gps服务器接收时间 + /// + public DateTime RecTime { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 方向 + /// + public int Direct { get; set; } + + /// + /// 速度 + /// + public int Speed { get; set; } + + /// + /// 静止时间 + /// + public string DurationTime { get; set; } + + /// + /// 打火状态 + /// + public int Acc { get; set; } + + /// + /// ACC持续时间 + /// + public string AccDurationTime + { + get => GpsState == 0 ? DurationTime : _accDurationTime; + set => _accDurationTime = value; + } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// SIM卡号 + /// + public string SimNo { get; set; } + + /// + /// 公司ID + /// + public long CompanyId { get; set; } + + /// + /// 修改时间 + /// + public DateTime ModifiedTime { get; set; } + + /// + /// 创建时间 + /// + public DateTime CreatedTime { get; set; } + + /// + /// 设备号 + /// + public string TerminalNo { get; set; } + + /// + /// 是否工作 + /// + public int Work { get; set; } + + /// + /// 工作时长 + /// + public string WorkDurationTime { get; set; } + + /// + /// Gps信号模式 1 GPS,2 基站 + /// + public int GpsMode { get; set; } + + /// + /// 位置基本信息报警标志位 --欠压 + /// + public int GpsAlert { get; set; } + /// + /// 掉电 + /// + public int Useing { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Collection/PgyAlertStraightDtl.cs b/src/Znyc.Dispatching.MongoDb.Repository/Collection/PgyAlertStraightDtl.cs new file mode 100644 index 0000000..92b9845 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Collection/PgyAlertStraightDtl.cs @@ -0,0 +1,57 @@ +using Pursue.Extension.MongoDB; +using System; + +namespace Znyc.Dispatching.MongoDb.Repository.Collection +{ + /// + /// 警报 + /// + public class PgyAlertStraightDtl : MongoEntityPrimaryKey + { + /// + /// 所属公司 + /// + public long CompanyId { get; set; } + + /// + /// 车辆自编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 方向 + /// + public int Direct { get; set; } + + /// + /// 速度 + /// + public int Speed { get; set; } + + /// + /// Gps数据产生时间 + /// + //[BsonDateTimeOptions(Kind = DateTimeKind.Unspecified)] + public DateTime GpsTime { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Collection/PgyAlertStraightLis.cs b/src/Znyc.Dispatching.MongoDb.Repository/Collection/PgyAlertStraightLis.cs new file mode 100644 index 0000000..96f99a1 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Collection/PgyAlertStraightLis.cs @@ -0,0 +1,72 @@ +using Pursue.Extension.MongoDB; +using System; + +namespace Znyc.Dispatching.MongoDb.Repository.Collection +{ + /// + /// 警报 + /// + public class PgyAlertStraightLis : MongoEntityPrimaryKey + { + // public object _id { get; set; } + /// + /// 车辆ID + /// + public long VehicleId { get; set; } + + /// + /// 公司id + /// + public long CompanyId { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// 车辆编号 + /// + public string VehicleCode { get; set; } + + /// + /// gps定位时间 + /// + public DateTime GpsTime { get; set; } + + /// + /// 设备名称(手机号) + /// + public string DeviceName { get; set; } + + /// + /// 报警类型 + /// + public string AlertTypeName { get; set; } + + /// + /// 连续超速第几个点,页面统计需要,轨迹连续点(超速的次数) + /// + public int ContinuteCount { get; set; } + + /// + /// 连续超速时长,页面统计需要,轨迹连续时长(超速的时长) + /// + public double ContinuteTimeLong { get; set; } + + /// + /// 报警最高速度 + /// + public int TopSpeed { get; set; } + + /// + /// 报警最低速度 + /// + public int LowSpeed { get; set; } + + /// + /// 主表的id,方便附表查询 + /// + public string AlertGuid { get; set; } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Collection/StopPointCalculation.cs b/src/Znyc.Dispatching.MongoDb.Repository/Collection/StopPointCalculation.cs new file mode 100644 index 0000000..41603f0 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Collection/StopPointCalculation.cs @@ -0,0 +1,51 @@ +using System; + +namespace Znyc.Dispatching.MongoDb.Repository.Collection +{ + public class StopPointCalculation + { + public object _id { get; set; } + + /// + /// 经度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// GPS时间 + /// + public DateTime StartTime { get; set; } + + /// + /// 状态 + /// + public int Status { get; set; } + + /// + /// 停留点描述 + /// + public string State { get; set; } + + /// + /// 停留时长描述 + /// + public string Behavior { get; set; } + + /// + /// 总里程 + /// + public decimal TotalDistance { get; set; } + + public DateTime EndTime { get; set; } + } +} diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Collection/VehicleGps.cs b/src/Znyc.Dispatching.MongoDb.Repository/Collection/VehicleGps.cs new file mode 100644 index 0000000..f410cbc --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Collection/VehicleGps.cs @@ -0,0 +1,95 @@ +using Pursue.Extension.MongoDB; +using System; + +namespace Znyc.Dispatching.MongoDb.Repository.Collection +{ + public class VehicleGps : MongoEntityPrimaryKey + { + + /// + /// 所属车辆 + /// + public long VehicleId { get; set; } + + /// + /// 所属公司 + /// + public long CompanyId { get; set; } + + /// + /// SIM卡号 + /// + public string SimNo { get; set; } + + /// + /// 车辆自编号 + /// + public string VehicleCode { get; set; } + + /// + /// 车牌号 + /// + public string VehiclePlate { get; set; } + + /// + /// 精度 + /// + public decimal Longitude { get; set; } + + /// + /// 纬度 + /// + public decimal Latitude { get; set; } + + /// + /// 速度 + /// + public int Speed { get; set; } + + /// + /// 方向 + /// + public int Direct { get; set; } + + /// + /// GPS状态 + /// + public int GpsState { get; set; } + + /// + /// Gps数据产生时间 + /// + //[BsonDateTimeOptions(Kind = DateTimeKind.Unspecified)] + public DateTime GpsTime { get; set; } + + /// + /// Gps服务器接收时间 + /// + //[BsonDateTimeOptions(Kind = DateTimeKind.Unspecified)] + public DateTime RecTime { get; set; } + + /// + /// ACC状态 + /// + public int Acc { get; set; } + + + /// + /// 是否工作 + /// + public int Work { get; set; } + + /// + /// 地址 + /// + public string Address { get; set; } + + /// + /// Gps信号模式 1 GPS,2 基站 + /// + public int GpsMode { get; set; } + + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IGpsRealTimeRepository.cs b/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IGpsRealTimeRepository.cs new file mode 100644 index 0000000..3c5a7b2 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IGpsRealTimeRepository.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.MongoDb.Repository.Repositorys +{ + public interface IGpsRealTimeRepository + { + Task InsertGpsRealTime(GpsRealTime gpsRealTime); + + Task GetGpsRealTimeByVehicleId(long vehicleId); + + Task> GetGpsRealTimeByCompanyId(long companyId); + + Task> GetOfflineGpsRealTime(); + + Task UpdateGpsRealTime(object id, GpsRealTime gpsRealTime); + + + Task> GetGpsRealTimeListByVehicleId(List vehicleIds); + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IMongodbBaseRepository.cs b/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IMongodbBaseRepository.cs new file mode 100644 index 0000000..a77360e --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IMongodbBaseRepository.cs @@ -0,0 +1,54 @@ +using MongoDB.Driver; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.MongoDb.Repository.Repositorys +{ + public interface IMongodbBaseRepository + { + /// + /// 查询车辆明细数据 + /// + /// + /// + /// + Task> GetVehicleGpsListAsync(string tbName, FilterDefinition filter); + + /// + /// 查询车辆停留点 + /// + /// + /// + Task> GetStopPointCalculationListAsync(string tbName); + + /// + /// 查询公司车辆超速数据最新100条 + /// + /// + /// + /// + Task> GetVehicleAlertListAsync(string tbName, + FilterDefinition filter); + + /// + /// 查询车辆超速分页数据 + /// + /// + /// + /// + /// + /// + Task> GetAlertPageAsync(string tbName, + FilterDefinition filter, int currentPage, int pageSize); + + /// + /// 查询车辆超速总条数 + /// + /// + /// + /// + Task GetAlertCountAsync(string tbName, + FilterDefinition filter); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IPgyAlertStraightDtlRepository.cs b/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IPgyAlertStraightDtlRepository.cs new file mode 100644 index 0000000..08143b0 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IPgyAlertStraightDtlRepository.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.MongoDb.Repository.Repositorys +{ + public interface IPgyAlertStraightDtlRepository + { + /// + /// 超速报警记录 + /// + /// + /// + Task> FindAlarmListByTime(long companyId); + + /// + /// 超速报警记录分页列表 + /// + /// + /// + /// + /// + Task> FindAlarmPageAsync(long companyId, int currentPage, int pageSize); + + /// + /// 超速报警记录总条数 + /// + /// + /// + Task FindAlarmCountAsync(long companyId); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IPgyAlertStraightLisRepository.cs b/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IPgyAlertStraightLisRepository.cs new file mode 100644 index 0000000..0938f80 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/IRepositorys/IPgyAlertStraightLisRepository.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.MongoDb.Repository.Repositorys +{ + public interface IPgyAlertStraightLisRepository + { + Task> FindAnalysisAlarmListByTime(string key, DateTime startDateTime, + DateTime endDateTime, long companyId, int lowSpeed, int topSpeed, int continuteCount); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/MongoContext.cs b/src/Znyc.Dispatching.MongoDb.Repository/MongoContext.cs new file mode 100644 index 0000000..9a0dc68 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/MongoContext.cs @@ -0,0 +1,23 @@ +using MongoDB.Driver; +using Pursue.Extension.MongoDB; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.MongoDb.Repository +{ + public class MongoContext : MongoDbContext + { + public MongoContext() : base() + { + + } + + // 上下文模式可以注入需要操作的实体对象和EF一样 + public IMongoCollection GpsRealTime => DbSet(); + + public IMongoCollection GpsCarAccDuration => DbSet(); + + public IMongoCollection PgyAlertStraightDtl => DbSet(); + + public IMongoCollection VehicleGps => DbSet(); + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/MongoDbStartup.cs b/src/Znyc.Dispatching.MongoDb.Repository/MongoDbStartup.cs new file mode 100644 index 0000000..199327a --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/MongoDbStartup.cs @@ -0,0 +1,28 @@ +using Furion; +using Microsoft.Extensions.DependencyInjection; +using Pursue.Extension.MongoDB; +using Znyc.Dispatching.MongoDb.Repository.Repositorys; + +namespace Znyc.Dispatching.MongoDb.Repository +{ + [AppStartup(80)] + public class MongoDbStartup : AppStartup + { + public void ConfigureServices(IServiceCollection services) + { + services.AddMongoDBContext(options => + { + options.UseMongo(App.Configuration["MongoDbConnectionStrings:DefaultConnection"], + App.Configuration["MongoDbConnectionStrings:Database"]); + }); + + services.AddMongoDbService(); + + services.AddTransient(); + + services.AddTransient(); + + services.AddTransient(); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/GpsRealTimeRepository.cs b/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/GpsRealTimeRepository.cs new file mode 100644 index 0000000..5e4a6fe --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/GpsRealTimeRepository.cs @@ -0,0 +1,86 @@ +using Pursue.Extension.MongoDB; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.MongoDb.Repository.Repositorys +{ + /// + /// gps服务 + /// + public class GpsRealTimeRepository : IGpsRealTimeRepository + { + private readonly IMongoDbRepository _gpsRealTimemongoDbRepository; + + public GpsRealTimeRepository(IMongoDbService context) + { + _gpsRealTimemongoDbRepository = context.GetRepository(); + ; + } + + /// + /// 新增数据 + /// + /// + /// + public async Task InsertGpsRealTime(GpsRealTime gpsRealTime) + { + await _gpsRealTimemongoDbRepository.AddAsync(gpsRealTime); + return true; + } + + /// + /// 根据车辆Id查询信息 + /// + /// + /// + public async Task GetGpsRealTimeByVehicleId(long vehicleId) + { + return await _gpsRealTimemongoDbRepository.QueryOneAsync(x => x.VehicleId == vehicleId); + } + + /// + /// 根据公司Id查询所有车辆信息 + /// + /// + /// + public async Task> GetGpsRealTimeByCompanyId(long companyId) + { + return await _gpsRealTimemongoDbRepository.QueryListAsync(x => x.CompanyId == companyId); + } + + /// + /// 查询所有离线车辆信息 + /// + /// + public async Task> GetOfflineGpsRealTime() + { + return await _gpsRealTimemongoDbRepository.QueryListAsync(x => + x.GpsState == (int)GpsStatusEnum.OFFLINE && x.Status == (int)CommonStatusEnum.ENABLE); + } + + /// + /// 修改车辆信息 + /// + /// + /// + /// + public async Task UpdateGpsRealTime(object id, GpsRealTime gpsRealTime) + { + await _gpsRealTimemongoDbRepository.UpdateAsync(id.ToString(), gpsRealTime); + } + + + /// + /// 根据车辆Id查询所有信息信息 + /// + /// + /// + public async Task> GetGpsRealTimeListByVehicleId(List vehicleIds) + { + return await _gpsRealTimemongoDbRepository.QueryListAsync(x => vehicleIds.Contains(x.VehicleId)); + } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/MongodbBaseRepository.cs b/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/MongodbBaseRepository.cs new file mode 100644 index 0000000..8e8a3d1 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/MongodbBaseRepository.cs @@ -0,0 +1,97 @@ +using Furion; +using MongoDB.Driver; +using Pursue.Extension.MongoDB; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.MongoDb.Repository.Repositorys +{ + /// + /// gps服务 + /// + public class MongodbBaseRepository : IMongodbBaseRepository + { + private readonly IMongoDbContext _context; + + public MongodbBaseRepository(IMongoDbContext context) + { + _context = context; + } + + /// + /// 查询车辆明细数据 + /// + /// + /// + public async Task> GetVehicleGpsListAsync(string tbName, FilterDefinition filter) + { + return await _context.GetDataBase(App.Configuration["MongoDbConnectionStrings:Database"]) + .GetCollection(tbName).Find(filter).ToListAsync(); + } + + /// + /// 查询车辆停留点 + /// + /// + /// + public async Task> GetStopPointCalculationListAsync(string tbName) + { + FilterDefinition filter = Builders.Filter.Gte("Status", -1); + return await _context.GetDataBase(App.Configuration["MongoDbConnectionStrings:Database"]) + .GetCollection(tbName).Find(filter).ToListAsync(); + } + + /// + /// 查询公司车辆超速数据最新100条 + /// + /// + /// + /// + public async Task> GetVehicleAlertListAsync(string tbName, + FilterDefinition filter) + { + return await _context.GetDataBase(App.Configuration["MongoDbConnectionStrings:Database"]) + .GetCollection(tbName) + .Find(filter) + .SortByDescending(x => x.GpsTime) + .Limit(100) + .ToListAsync(); + } + + /// + /// 查询车辆超速分页数据 + /// + /// + /// + /// + /// + /// + public async Task> GetAlertPageAsync(string tbName, + FilterDefinition filter, int currentPage, int pageSize) + { + return await _context.GetDataBase(App.Configuration["MongoDbConnectionStrings:Database"]) + .GetCollection(tbName) + .Find(filter) + .SortByDescending(x => x.GpsTime) + .Limit(pageSize) + .Skip((currentPage - 1) * pageSize) + .ToListAsync(); + } + + /// + /// 查询车辆超速总条数 + /// + /// + /// + /// + public async Task GetAlertCountAsync(string tbName, + FilterDefinition filter) + { + return await _context.GetDataBase(App.Configuration["MongoDbConnectionStrings:Database"]) + .GetCollection(tbName).Find(filter).CountDocumentsAsync(); + } + + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/PgyAlertStraightDtlRepository.cs b/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/PgyAlertStraightDtlRepository.cs new file mode 100644 index 0000000..70511ca --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/PgyAlertStraightDtlRepository.cs @@ -0,0 +1,87 @@ +using Microsoft.AspNetCore.Mvc; +using MongoDB.Driver; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.MongoDb.Repository.Repositorys +{ + /// + /// gps警报服务 + /// + [ApiDescriptionSettings(ApiGroupConsts.LOG_CENTER, Name = "gps", Order = 100, IgnoreApi = true)] + public class PgyAlertStraightDtlRepository : IPgyAlertStraightDtlRepository + { + private readonly IMongodbBaseRepository _mongodbBaseRepository; + + public PgyAlertStraightDtlRepository(IMongodbBaseRepository mongodbBaseRepository) + { + _mongodbBaseRepository = mongodbBaseRepository; + } + + /// + /// 超速报警记录 + /// + /// + /// + public async Task> FindAlarmListByTime(long companyId) + { + string syear = DateTime.Now.ToString("yyyyMM"); + string tableName = CommonConst.DEFAULT_ALARMSTRAIGHT_PREFIX + syear; + FilterDefinition filter = null; + if (companyId > 0) + { + filter = Builders.Filter.Eq("CompanyId", companyId); + } + //if (vehicleId > 0) + // filter = filter & (Builders.Filter.Eq("VehicleId", vehicleId)); + //if (overSpeed > 0) + // filter = filter & (Builders.Filter.Gte("Speed", overSpeed)); + List list = await _mongodbBaseRepository.GetVehicleAlertListAsync(tableName, filter); + return list; + } + + /// + /// 超速报警记录分页列表 + /// + /// + /// + /// + /// + public async Task> FindAlarmPageAsync(long companyId, int currentPage, int pageSize) + { + string syear = DateTime.Now.ToString("yyyyMM"); + string tableName = CommonConst.DEFAULT_ALARMSTRAIGHT_PREFIX + syear; + FilterDefinition filter = null; + if (companyId > 0) + { + filter = Builders.Filter.Eq("CompanyId", companyId); + } + + List list = await _mongodbBaseRepository.GetAlertPageAsync(tableName, filter, currentPage, pageSize); + return list; + } + + /// + /// 超速报警记录总条数 + /// + /// + /// + public async Task FindAlarmCountAsync(long companyId) + { + string syear = DateTime.Now.ToString("yyyyMM"); + string tableName = CommonConst.DEFAULT_ALARMSTRAIGHT_PREFIX + syear; + FilterDefinition filter = null; + if (companyId > 0) + { + filter = Builders.Filter.Eq("CompanyId", companyId); + } + + long count = await _mongodbBaseRepository.GetAlertCountAsync(tableName, filter); + return count; + } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/PgyAlertStraightLisRepository.cs b/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/PgyAlertStraightLisRepository.cs new file mode 100644 index 0000000..90e0bc3 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Repositorys/PgyAlertStraightLisRepository.cs @@ -0,0 +1,71 @@ +using MongoDB.Driver; +using Pursue.Extension.MongoDB; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Znyc.Dispatching.MongoDb.Repository.Collection; + +namespace Znyc.Dispatching.MongoDb.Repository.Repositorys +{ + /// + /// gps警报服务 + /// + public class PgyAlertStraightLisRepository : IPgyAlertStraightLisRepository + { + private readonly IMongoDbRepository _pgyAlertStraightLisRepository; + + public PgyAlertStraightLisRepository(IMongoDbService context) + { + _pgyAlertStraightLisRepository = context.GetRepository(); + ; + } + + /// + /// 直线/弯道报警,主表记录 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> FindAnalysisAlarmListByTime(string key, DateTime startDateTime, + DateTime endDateTime, long companyId, int lowSpeed, int topSpeed, int continuteCount) + { + string syear = startDateTime.ToString("yyyyMM"); + FilterDefinition filter = Builders.Filter.Gte("GpsTime", startDateTime) + & Builders.Filter.Lt("GpsTime", endDateTime); + if (!string.IsNullOrEmpty(key)) + { + filter &= (Builders.Filter.Regex("VehiclePlate", key) | + Builders.Filter.Regex("VehicleCode", key)); + } + + if (companyId != 0) + { + filter &= Builders.Filter.Eq("CompanyId", companyId); + } + + if (lowSpeed != 0) + { + filter &= Builders.Filter.Gte("LowSpeed", lowSpeed); + } + + if (topSpeed != 0) + { + filter &= Builders.Filter.Gte("TopSpeed", topSpeed); + } + + if (continuteCount != 0) + { + filter &= Builders.Filter.Gte("ContinuteCount", continuteCount); + } + + List list = await _pgyAlertStraightLisRepository.QueryListAsync(filter); + return list; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/Znyc.Dispatching.MongoDb.Repository.csproj b/src/Znyc.Dispatching.MongoDb.Repository/Znyc.Dispatching.MongoDb.Repository.csproj new file mode 100644 index 0000000..c585f7f --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/Znyc.Dispatching.MongoDb.Repository.csproj @@ -0,0 +1,34 @@ + + + + net6.0 + + + + + + + + + + + Always + + + Always + + + Always + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/mongodbsettings.Development.json b/src/Znyc.Dispatching.MongoDb.Repository/mongodbsettings.Development.json new file mode 100644 index 0000000..ed7ea68 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/mongodbsettings.Development.json @@ -0,0 +1,7 @@ +{ + "MongoDbConnectionStrings": { + "DefaultConnection": "mongodb://42.194.147.251:27018", + //"DefaultConnection": "mongodb://127.0.0.1:27017", + "Database": "ZNYCGPS" + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/mongodbsettings.Production.json b/src/Znyc.Dispatching.MongoDb.Repository/mongodbsettings.Production.json new file mode 100644 index 0000000..cee2788 --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/mongodbsettings.Production.json @@ -0,0 +1,6 @@ +{ + "MongoDbConnectionStrings": { + "DefaultConnection": "mongodb://172.16.0.16:27017", + "Database": "ZNYCGPS" + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.MongoDb.Repository/mongodbsettings.Staging.json b/src/Znyc.Dispatching.MongoDb.Repository/mongodbsettings.Staging.json new file mode 100644 index 0000000..6ff716d --- /dev/null +++ b/src/Znyc.Dispatching.MongoDb.Repository/mongodbsettings.Staging.json @@ -0,0 +1,7 @@ +{ + "MongoDbConnectionStrings": { + //"DefaultConnection": "mongodb://root:D#Du17p$UYMNh@42.194.147.251:27017", + "DefaultConnection": "mongodb://10.0.8.5:27018", + "Database": "ZNYCGPS" + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Tasks/HangfireDispose.cs b/src/Znyc.Dispatching.Tasks/HangfireDispose.cs new file mode 100644 index 0000000..2ef950a --- /dev/null +++ b/src/Znyc.Dispatching.Tasks/HangfireDispose.cs @@ -0,0 +1,47 @@ +using Hangfire; +using System; +using Znyc.Dispatching.Tasks.TaskJobs; + +namespace Znyc.Dispatching.Tasks +{ + public class HangfireDispose + { + + public static void HangfireService() + { + //Fire - And - forget(发布 / 订阅) + //这是一个主要的后台任务类型,持久化消息队列会去处理这个任务。当你创建了一个发布 / 订阅任务,该任务会被保存到默认队列里面(默认队列是"Default",但是支持使用多队列)。多个专注的工作者(Worker)会监听这个队列,并且从中获取任务并且完成任务。 + //BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget")); + + //延迟 + //如果想要延迟某些任务的执行,可以是用以下任务。在给定延迟时间后,任务会被排入队列,并且和发布 / 订阅任务一样执行。 + //BackgroundJob.Schedule(() => Console.WriteLine("Delayed"), TimeSpan.FromDays(1)); + + //循环 + //按照周期性(小时,天等)来调用方法,请使用RecurringJob类。在复杂的场景,您可以使用CRON表达式指定计划时间来处理任务。 + //RecurringJob.AddOrUpdate(() => Console.WriteLine("Daily Job"), Cron.Daily); + + //连续 + //连续性允许您通过将多个后台任务链接在一起来定义复杂的工作流。 + //var id = BackgroundJob.Enqueue(() => Console.WriteLine("Hello, ")); + //BackgroundJob.ContinueWith(id, () => Console.WriteLine("world!")); + + //这里呢就是需要触发的方法 "0/10 * * * * ? " 可以自行搜索cron表达式 代表循环的规律很简单 + //CancelOrderJob代表你要触发的类 Execute代表你要触发的方法 + + //每十分钟预热今天的轨迹 + // RecurringJob.AddOrUpdate(s => s.Execute(), "0 0/10 * * * ? ", TimeZoneInfo.Utc); + //每晚预热昨天的轨迹 + //RecurringJob.AddOrUpdate(s => s.Execute(), "0 0 0 */1 * ? ", TimeZoneInfo.Utc); + + //每30天预热一次角色菜单缓存 + RecurringJob.AddOrUpdate(s => s.RoleMenuExecuteAsync(), "0 0 5 1 * ? ", TimeZoneInfo.Local); + + + RecurringJob.AddOrUpdate(s => s.SyncOrderStatusAsync(), "0 0/1 * * * ? ", TimeZoneInfo.Local); + + + + } + } +} diff --git a/src/Znyc.Dispatching.Tasks/TaskJobs/AutoEveryNightTrackPlaybackCorrectionJob.cs b/src/Znyc.Dispatching.Tasks/TaskJobs/AutoEveryNightTrackPlaybackCorrectionJob.cs new file mode 100644 index 0000000..ad99b85 --- /dev/null +++ b/src/Znyc.Dispatching.Tasks/TaskJobs/AutoEveryNightTrackPlaybackCorrectionJob.cs @@ -0,0 +1,23 @@ +using System; +using System.Threading.Tasks; +using Znyc.Dispatching.Application; + +namespace Znyc.Dispatching.Tasks.TaskJobs +{ + + public class AutoTrackPlaybackCorrectionJob + { + private readonly IVehicleService _vehicleService; + + + public AutoTrackPlaybackCorrectionJob(IVehicleService vehicleService) + { + _vehicleService = vehicleService; + } + + public async Task Execute() + { + await _vehicleService.SyncTrackPlaybackCorrectionAsync(DateTime.Now.Date, DateTime.Now, "Yesterday"); + } + } +} diff --git a/src/Znyc.Dispatching.Tasks/TaskJobs/AutoOrderJob.cs b/src/Znyc.Dispatching.Tasks/TaskJobs/AutoOrderJob.cs new file mode 100644 index 0000000..98deea2 --- /dev/null +++ b/src/Znyc.Dispatching.Tasks/TaskJobs/AutoOrderJob.cs @@ -0,0 +1,28 @@ +using Dilon.Core.Service; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.Tasks.TaskJobs +{ + /// + /// + /// + public class AutoOrderJob + { + private readonly IJobService _jobService; + + public AutoOrderJob(IJobService JobService) + { + _jobService = JobService; + + } + + /// + /// + /// + /// + public async Task SyncOrderStatusAsync() + { + await _jobService.SyncOrderStatusAsync(); + } + } +} diff --git a/src/Znyc.Dispatching.Tasks/TaskJobs/AutoRoleMenuJob.cs b/src/Znyc.Dispatching.Tasks/TaskJobs/AutoRoleMenuJob.cs new file mode 100644 index 0000000..374ebcc --- /dev/null +++ b/src/Znyc.Dispatching.Tasks/TaskJobs/AutoRoleMenuJob.cs @@ -0,0 +1,38 @@ +using System.Threading.Tasks; +using Znyc.Dispatching.Application; + +namespace Znyc.Dispatching.Tasks.TaskJobs +{ + /// + /// 角色菜单定时任务 + /// + public class AutoRoleMenuJob + { + private readonly IRoleService _roleService; + private readonly IRoleMenuService _roleMenuService; + private readonly ICacheService _cacheService; + + public AutoRoleMenuJob(IRoleService roleService, + ICacheService cacheService, + IRoleMenuService roleMenuService) + { + _roleService = roleService; + _roleMenuService = roleMenuService; + _cacheService = cacheService; + } + + /// + /// 同步角色菜单缓存 + /// + /// + public async Task RoleMenuExecuteAsync() + { + //同步角色缓存 + var role = await _roleService.GetRoleAsync(); + foreach (var item in role) + { + await _roleMenuService.GetRoleMenuListByIdAsync(item.Id); + } + } + } +} diff --git a/src/Znyc.Dispatching.Tasks/TaskJobs/AutoTrackPlaybackCorrectionJob.cs b/src/Znyc.Dispatching.Tasks/TaskJobs/AutoTrackPlaybackCorrectionJob.cs new file mode 100644 index 0000000..f3cdbda --- /dev/null +++ b/src/Znyc.Dispatching.Tasks/TaskJobs/AutoTrackPlaybackCorrectionJob.cs @@ -0,0 +1,23 @@ +using System; +using System.Threading.Tasks; +using Znyc.Dispatching.Application; + +namespace Znyc.Dispatching.Tasks.TaskJobs +{ + + public class AutoEveryNightTrackPlaybackCorrectionJob + { + private readonly IVehicleService _vehicleService; + + + public AutoEveryNightTrackPlaybackCorrectionJob(IVehicleService vehicleService) + { + _vehicleService = vehicleService; + } + + public async Task Execute() + { + await _vehicleService.SyncTrackPlaybackCorrectionAsync(DateTime.Now.AddDays(-1).Date, DateTime.Now.Date.AddMinutes(-1), "Today"); + } + } +} diff --git a/src/Znyc.Dispatching.Tasks/TasksStartup.cs b/src/Znyc.Dispatching.Tasks/TasksStartup.cs new file mode 100644 index 0000000..97fbe2b --- /dev/null +++ b/src/Znyc.Dispatching.Tasks/TasksStartup.cs @@ -0,0 +1,69 @@ +using Furion; +using Hangfire; +using Hangfire.Dashboard.BasicAuthorization; +using Hangfire.Redis; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using System; +using Znyc.Dispatching.Core.Enums; +using Znyc.Dispatching.Tasks; + +namespace Znyc.Dispatching.MongoDb.Repository +{ + [AppStartup(95)] + public class TasksStartup : AppStartup + { + public void ConfigureServices(IServiceCollection services) + { + services.AddHangfire(x => x.UseRedisStorage(App.Configuration["Cache:RedisConnectionString"])); + services.AddHangfireServer(options => + { + options.Queues = new[] { HangFireQueuesConfig.@default.ToString(), HangFireQueuesConfig.apis.ToString(), HangFireQueuesConfig.web.ToString(), HangFireQueuesConfig.recurring.ToString() }; + options.ServerTimeout = TimeSpan.FromMinutes(4); + options.SchedulePollingInterval = TimeSpan.FromSeconds(15);//秒级任务需要配置短点,一般任务可以配置默认时间,默认15秒 + options.ShutdownTimeout = TimeSpan.FromMinutes(30); //超时时间 + options.WorkerCount = Math.Max(Environment.ProcessorCount, 20); //工作线程数,当前允许的最大线程,默认20 + }); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { //授权 + var filter = new BasicAuthAuthorizationFilter( + new BasicAuthAuthorizationFilterOptions + { + SslRedirect = false, + // Require secure connection for dashboard + RequireSsl = false, + // Case sensitive login checking + LoginCaseSensitive = false, + // Users + Users = new[] + { + new BasicAuthAuthorizationUser + { + Login = App.Configuration["Hangfire:Login"], + PasswordClear = App.Configuration["Hangfire:Password"] + } + } + }); + + var options = new DashboardOptions + { + AppPath = "/",//返回时跳转的地址 + DisplayStorageConnectionString = false,//是否显示数据库连接信息 + Authorization = new[] + { + filter + }, + IsReadOnlyFunc = Context => + { + return false;//是否只读面板 + } + }; + + app.UseHangfireDashboard("/dc_job", options); + HangfireDispose.HangfireService(); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Tasks/Znyc.Dispatching.Tasks.csproj b/src/Znyc.Dispatching.Tasks/Znyc.Dispatching.Tasks.csproj new file mode 100644 index 0000000..389e8de --- /dev/null +++ b/src/Znyc.Dispatching.Tasks/Znyc.Dispatching.Tasks.csproj @@ -0,0 +1,19 @@ + + + + net6.0 + + + + + + + + + + + + + + + diff --git a/src/Znyc.Dispatching.WeChat.Core/CommonService/SubscribeMessage/WxApplet/WxAppletSubscribeMessage.cs b/src/Znyc.Dispatching.WeChat.Core/CommonService/SubscribeMessage/WxApplet/WxAppletSubscribeMessage.cs new file mode 100644 index 0000000..0550047 --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/CommonService/SubscribeMessage/WxApplet/WxAppletSubscribeMessage.cs @@ -0,0 +1,109 @@ +using Furion; +using Senparc.Weixin.Entities; +using Senparc.Weixin.Entities.TemplateMessage; +using Senparc.Weixin.WxOpen.AdvancedAPIs; + +namespace Znyc.Dispatching.WeChat.Core.CommonService.SubscribeMessage.WxApplet +{ + /// + /// 小程序订阅消息 + /// + public class WxAppletSubscribeMessage + { + private static readonly string wxOpenAppId = App.Configuration["SenparcWeixinSetting:WxOpenAppId"]; + + /// + /// 留言提醒,模板编号:1069 + /// + /// 接收者(用户)的 openid + /// 消息模板Id + /// 留言内容,20个以内字符 + /// 留言时间,4小时制时间格式(支持+年月日) 例如:15:01,或:2019年10月1日 15:01 + /// 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 + public static WxJsonResult SendCommentNotice(string toUser, string templateId, string text, string date, + string page) + { + TemplateMessageData data = new TemplateMessageData + { + ["thing1"] = new(text), + ["time2"] = new(date) + }; + var submitData = new + { + touser = toUser, + template_id = templateId, + page, + data + }; + return MessageApi.SendSubscribe(wxOpenAppId, toUser, templateId, data, page); + } + + /// + /// 新的评论提醒 ,模板编号:484 + /// + /// 接收者(用户)的 openid + /// 消息模板Id + /// 文章标题,20个以内字符 + /// 评论内容,20个以内字符 + /// 评论时间,4小时制时间格式(支持+年月日) 例如:15:01,或:2019年10月1日 15:01 + /// 评论用户,20个以内字符 + /// + public static WxJsonResult SendRemarkNotice(string toUser, string templateId, string title, string desc, + string date, string userNick, string page) + { + TemplateMessageData data = new TemplateMessageData + { + {"thing1", new TemplateMessageDataValue(title)}, + {"thing2", new TemplateMessageDataValue(desc)}, + {"time3", new TemplateMessageDataValue(date)}, + {"thing5", new TemplateMessageDataValue(userNick)} + }; + return MessageApi.SendSubscribe(wxOpenAppId, toUser, templateId, data, page); + } + + /// + /// 动态点赞通知,模板编号:579 + /// + /// 接收者(用户)的 openid + /// 消息模板Id + /// 点赞用户,20个以内字符 + /// 点赞时间,4小时制时间格式(支持+年月日) 例如:15:01,或:2019年10月1日 15:01 + /// 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 + public static WxJsonResult SendGoodNotice(string toUser, string templateId, string name, string date, + string page) + { + TemplateMessageData data = new TemplateMessageData + { + {"name1", new TemplateMessageDataValue(name)}, + {"date2", new TemplateMessageDataValue(date)} + }; + return MessageApi.SendSubscribe(wxOpenAppId, toUser, templateId, data, page); + } + + /// + /// 资讯早报通知,模板编号:269 + /// + /// 接收者(用户)的 openid + /// 消息模板Id + /// 更新内容,20个以内字符 + /// 备注,20个以内字符 + /// 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 + public static WxJsonResult SendNewsMorningNotice(string toUser, string templateId, string title, string remark, + string page) + { + TemplateMessageData data = new TemplateMessageData + { + ["thing1"] = new(title), + ["thing2"] = new(remark) + }; + var submitData = new + { + touser = toUser, + template_id = templateId, + page, + data + }; + return MessageApi.SendSubscribe(wxOpenAppId, toUser, templateId, data, page); + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/Weixin/WeixinTemplateApi.cs b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/Weixin/WeixinTemplateApi.cs new file mode 100644 index 0000000..2b3df92 --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/Weixin/WeixinTemplateApi.cs @@ -0,0 +1,8 @@ +namespace Znyc.Dispatching.WeChat.Core.CommonService.TemplateMessage.Weixin +{ + public static class WeixinTemplateApi + { + + + } +} diff --git a/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/Weixin/WeixinTemplate_AssignOrder.cs b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/Weixin/WeixinTemplate_AssignOrder.cs new file mode 100644 index 0000000..edaa9d9 --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/Weixin/WeixinTemplate_AssignOrder.cs @@ -0,0 +1,51 @@ + + +using Senparc.Weixin.Entities.TemplateMessage; +using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage; + +namespace Znyc.Dispatching.WeChat.Core.CommonService.TemplateMessage +{ + + /* + {{first.DATA}} + 项目名称:{{keyword1.DATA}} + 工单类型:{{keyword2.DATA}} + 工作内容:{{keyword3.DATA}} + 日期时间:{{keyword4.DATA}} + {{remark.DATA}} + */ + + /// + /// + /// + public class WeixinTemplate_AssignOrder : TemplateMessageBase + { + const string TEMPLATE_ID = "tOuu24WtROB03z3VQnwiyg1oEJB_Q-fa_-11Gno4FZc"; + + public TemplateDataItem first { get; set; } + + public TemplateDataItem keyword1 { get; set; } + + public TemplateDataItem keyword2 { get; set; } + + public TemplateDataItem keyword3 { get; set; } + + public TemplateDataItem keyword4 { get; set; } + + /// + /// + /// + public TemplateDataItem remark { get; set; } + + public WeixinTemplate_AssignOrder(string _first, string projectName, string orderType, string orderContent, string ArriveDate, string _remark, string url = null, string templateId = TEMPLATE_ID) + : base(templateId, url, "派车通知") + { + first = new TemplateDataItem(_first); + keyword1 = new TemplateDataItem(projectName); + keyword2 = new TemplateDataItem(orderType); + keyword3 = new TemplateDataItem(orderContent); + keyword4 = new TemplateDataItem(ArriveDate); + remark = new TemplateDataItem(_remark); + } + } +} diff --git a/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/WxOpen/CommonApi.cs b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/WxOpen/CommonApi.cs new file mode 100644 index 0000000..3865c3b --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/WxOpen/CommonApi.cs @@ -0,0 +1,230 @@ +using Senparc.CO2NET.Extensions; +using Senparc.CO2NET.HttpUtility; +using Senparc.Weixin; +using Senparc.Weixin.CommonAPIs; +using Senparc.Weixin.Entities; +using Senparc.Weixin.Exceptions; +using Senparc.Weixin.MP; +using Senparc.Weixin.MP.Containers; +using Senparc.Weixin.MP.Entities; +using System.Threading.Tasks; +using Znyc.Dispatching.Core.Extension; + +namespace Znyc.Dispatching.WeChat.Core.CommonService.TemplateMessage.WxOpen +{ + /// + /// 通用接口 + /// 通用接口用于和微信服务器通讯,一般不涉及自有网站服务器的通讯 + /// + public static class CommonApi + { + #region 同步方法 + + /// + /// 获取凭证接口 + /// + /// 获取access_token填写client_credential + /// 第三方用户唯一凭证 + /// 第三方用户唯一凭证密钥,既appsecret + /// + public static AccessTokenResult GetToken(string appid, string secret, string grant_type = "client_credential") + { + //注意:此方法不能再使用ApiHandlerWapper.TryCommonApi(),否则会循环 + string url = string.Format(Config.ApiMpHost + "/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", + grant_type.AsUrlData(), appid.AsUrlData(), secret.AsUrlData()); + + AccessTokenResult result = Get.GetJson(CommonDI.CommonSP, url); //此处为最原始接口,不再使用重试获取的封装 + + if (Config.ThrownWhenJsonResultFaild && result.errcode != ReturnCode.请求成功) + { + throw new ErrorJsonResultException( + string.Format("微信请求发生错误(CommonApi.GetToken)!错误代码:{0},说明:{1}", + (int)result.errcode, result.errmsg), null, result); + } + + return result; + } + + + /// + /// 获取调用微信JS接口的临时票据 + /// + /// + /// + /// 默认为jsapi,当作为卡券接口使用时,应当为wx_card + /// + public static JsApiTicketResult GetTicket(string appId, string secret, string type = "jsapi") + { + string accessToken = AccessTokenContainer.TryGetAccessToken(appId, secret); + return GetTicketByAccessToken(accessToken, type); + } + + /// + /// 获取调用微信JS接口的临时票据 + /// + /// AccessToken或AppId(推荐使用AppId,需要先注册) + /// 默认为jsapi,当作为卡券接口使用时,应当为wx_card + /// + public static JsApiTicketResult GetTicketByAccessToken(string accessTokenOrAppId, string type = "jsapi") + { + return ApiHandlerWapper.TryCommonApi(accessToken => + { + string url = string.Format(Config.ApiMpHost + "/cgi-bin/ticket/getticket?access_token={0}&type={1}", + accessToken.AsUrlData(), type.AsUrlData()); + + JsApiTicketResult result = CommonJsonSend.Send(null, url, null, CommonJsonSendType.GET); + return result; + }, accessTokenOrAppId); + } + + /// + /// 获取微信服务器的ip段 + /// + /// AccessToken或AppId(推荐使用AppId,需要先注册) + /// + public static GetCallBackIpResult GetCallBackIp(string accessTokenOrAppId) + { + return ApiHandlerWapper.TryCommonApi(accessToken => + { + string url = string.Format(Config.ApiMpHost + "/cgi-bin/getcallbackip?access_token={0}", + accessToken.AsUrlData()); + + return CommonJsonSend.Send(null, url, null, CommonJsonSendType.GET); + }, accessTokenOrAppId); + } + + /// + /// 公众号调用或第三方平台帮公众号调用对公众号的所有api调用(包括第三方帮其调用)次数进行清零 + /// + /// AccessToken或AppId(推荐使用AppId,需要先注册) + /// + /// + /// + public static WxJsonResult Clear_quota(string accessTokenOrAppId, string appId, int timeOut = Config.TIME_OUT) + { + return ApiHandlerWapper.TryCommonApi(accessToken => + { + string urlFormat = string.Format(Config.ApiMpHost + "/cgi-bin/clear_quota?access_token={0}", + accessToken.AsUrlData()); + var data = new + { + appid = appId + }; + + return CommonJsonSend.Send(null, urlFormat, data, timeOut: timeOut); + }, accessTokenOrAppId); + } + + #endregion 同步方法 + + #region 异步方法 + + /// + /// 【异步方法】获取凭证接口 + /// + /// 获取access_token填写client_credential + /// 第三方用户唯一凭证 + /// 第三方用户唯一凭证密钥,既appsecret + /// + public static async Task GetTokenAsync(string appid, string secret, + string grant_type = "client_credential") + { + AccessTokenResult result; + result = await RedisHelper.GetAsync(appid); + if (result.IsNull()) + { + string url = string.Format(Config.ApiMpHost + "/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", + grant_type.AsUrlData(), appid.AsUrlData(), secret.AsUrlData()); + + result = await Get.GetJsonAsync(CommonDI.CommonSP, url); //此处为最原始接口,不再使用重试获取的封装 + + if (Config.ThrownWhenJsonResultFaild && result.errcode != ReturnCode.请求成功) + { + throw new ErrorJsonResultException( + string.Format("微信请求发生错误(CommonApi.GetToken)!错误代码:{0},说明:{1}", + (int)result.errcode, result.errmsg), null, result); + } + + await RedisHelper.SetAsync(appid, result, 7200); + } + + return result; + } + + + /// + /// 【异步方法】获取调用微信JS接口的临时票据 + /// + /// + /// + /// 默认为jsapi,当作为卡券接口使用时,应当为wx_card + /// + public static async Task GetTicketAsync(string appId, string secret, string type = "jsapi") + { + string accessToken = await AccessTokenContainer.TryGetAccessTokenAsync(appId, secret).ConfigureAwait(false); + return GetTicketByAccessToken(accessToken, type); + } + + /// + /// 【异步方法】获取调用微信JS接口的临时票据 + /// + /// AccessToken或AppId(推荐使用AppId,需要先注册) + /// 默认为jsapi,当作为卡券接口使用时,应当为wx_card + /// + public static async Task GetTicketByAccessTokenAsync(string accessTokenOrAppId, + string type = "jsapi") + { + return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => + { + string url = string.Format(Config.ApiMpHost + "/cgi-bin/ticket/getticket?access_token={0}&type={1}", + accessToken.AsUrlData(), type.AsUrlData()); + + Task result = CommonJsonSend.SendAsync(null, url, null, CommonJsonSendType.GET); + return await result.ConfigureAwait(false); + }, accessTokenOrAppId).ConfigureAwait(false); + } + + /// + /// 【异步方法】获取微信服务器的ip段 + /// + /// AccessToken或AppId(推荐使用AppId,需要先注册) + /// + public static async Task GetCallBackIpAsync(string accessTokenOrAppId) + { + return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => + { + string url = string.Format(Config.ApiMpHost + "/cgi-bin/getcallbackip?access_token={0}", + accessToken.AsUrlData()); + + return await CommonJsonSend.SendAsync(null, url, null, CommonJsonSendType.GET) + .ConfigureAwait(false); + }, accessTokenOrAppId).ConfigureAwait(false); + } + + /// + /// 【异步方法】公众号调用或第三方平台帮公众号调用对公众号的所有api调用(包括第三方帮其调用)次数进行清零 + /// + /// AccessToken或AppId(推荐使用AppId,需要先注册) + /// + /// + /// + public static async Task Clear_quotaAsync(string accessTokenOrAppId, string appId, + int timeOut = Config.TIME_OUT) + { + return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => + { + string urlFormat = string.Format(Config.ApiMpHost + "/cgi-bin/clear_quota?access_token={0}", + accessToken.AsUrlData()); + var data = new + { + appid = appId + }; + + return await CommonJsonSend.SendAsync(null, urlFormat, data, timeOut: timeOut) + .ConfigureAwait(false); + }, accessTokenOrAppId).ConfigureAwait(false); + } + + #endregion 异步方法 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/WxOpen/SnsApi.cs b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/WxOpen/SnsApi.cs new file mode 100644 index 0000000..74f0eec --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/WxOpen/SnsApi.cs @@ -0,0 +1,35 @@ +using Senparc.Weixin; +using Senparc.Weixin.CommonAPIs; +using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.WeChat.Core.CommonService.TemplateMessage.WxOpen +{ + /// + /// WxApp接口 + /// + public static class SnsApi + { + /// + /// 【异步方法】code 换取 session_key + /// + /// + /// + /// + /// 保持默认:authorization_code + /// 请求超时时间 + /// + public static async Task JsCode2JsonAsync(string appId, string secret, string jsCode, + string grantType = "authorization_code", int timeOut = Config.TIME_OUT) + { + string urlFormat = + Config.ApiMpHost + "/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type={3}"; + + string url = string.Format(urlFormat, appId, secret, jsCode, grantType); + + JsCode2JsonResult result = await CommonJsonSend.SendAsync(null, url, null, CommonJsonSendType.GET) + .ConfigureAwait(false); + return result; + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/WxOpen/WxOpenTemplateMessage_AssignOrder.cs b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/WxOpen/WxOpenTemplateMessage_AssignOrder.cs new file mode 100644 index 0000000..4dfb5cb --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/CommonService/TemplateMessage/WxOpen/WxOpenTemplateMessage_AssignOrder.cs @@ -0,0 +1,43 @@ +//DPBMARK_FILE MiniProgram + +using Senparc.Weixin.Entities.TemplateMessage; +using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage; + +namespace Znyc.Dispatching.WeChat.Core.CommonService.TemplateMessage.WxOpen +{ + public class WxOpenTemplateMessage_AssignOrder : TemplateMessageBase + { + /// + /// “派车通知”模板消息数据 + /// + /// 出车时间 + /// 用车部门 + /// 目的地 + /// + /// + public WxOpenTemplateMessage_AssignOrder( + string ArriveDate, string address, + string url, + string templateId = "zSVi_wYuuK7E4YoU3axdDT2_oiw-JvXYXi-tRl4X1aU", + string department = "") + : base(templateId, url, "派车通知") + { + /* + 关键词 + 出车时间 {{keyword1.DATA}} + 用车部门 {{keyword2.DATA}} + 目的地 {{keyword3.DATA}} + {{remark.DATA}} + */ + + keyword1 = new TemplateDataItem(ArriveDate); + keyword2 = new TemplateDataItem(department); + keyword3 = new TemplateDataItem(address); + } + + public TemplateDataItem keyword1 { get; set; } + public TemplateDataItem keyword2 { get; set; } + public TemplateDataItem keyword3 { get; set; } + + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.WeChat.Core/Helper/SnsHelper.cs b/src/Znyc.Dispatching.WeChat.Core/Helper/SnsHelper.cs new file mode 100644 index 0000000..6b12228 --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/Helper/SnsHelper.cs @@ -0,0 +1,62 @@ +using Senparc.Weixin; +using Senparc.Weixin.CommonAPIs; +using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns; +using System.Threading.Tasks; + +namespace Znyc.Dispatching.WeChat.Core.Helper +{ /// + /// WxApp接口 + /// + public static class SnsHelper + { + #region 同步方法 + + /// + /// code 换取 session_key + /// + /// + /// + /// + /// 保持默认:authorization_code + /// 请求超时时间 + /// + public static JsCode2JsonResult JsCode2Json(string appId, string secret, string jsCode, + string grantType = "authorization_code", int timeOut = Config.TIME_OUT) + { + string urlFormat = + Config.ApiMpHost + "/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type={3}"; + + string url = string.Format(urlFormat, appId, secret, jsCode, grantType); + JsCode2JsonResult result = CommonJsonSend.Send(null, url, null, CommonJsonSendType.GET); + return result; + } + + #endregion 同步方法 + + #region 异步方法 + + /// + /// 【异步方法】code 换取 session_key + /// + /// + /// + /// + /// 保持默认:authorization_code + /// 请求超时时间 + /// + public static async Task JsCode2JsonAsync(string appId, string secret, string jsCode, + string grantType = "authorization_code", int timeOut = Config.TIME_OUT) + { + string urlFormat = + Config.ApiMpHost + "/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type={3}"; + + string url = string.Format(urlFormat, appId, secret, jsCode, grantType); + + JsCode2JsonResult result = await CommonJsonSend.SendAsync(null, url, null, CommonJsonSendType.GET) + .ConfigureAwait(false); + return result; + } + + #endregion 异步方法 + } +} diff --git a/src/Znyc.Dispatching.WeChat.Core/WeChatStartup.cs b/src/Znyc.Dispatching.WeChat.Core/WeChatStartup.cs new file mode 100644 index 0000000..5cd22f7 --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/WeChatStartup.cs @@ -0,0 +1,33 @@ +using Furion; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Senparc.CO2NET; +using Senparc.CO2NET.RegisterServices; +using Senparc.Weixin.Entities; +using Senparc.Weixin.MP.Containers; +using Senparc.Weixin.RegisterServices; + +namespace Znyc.Dispatching.WeChat.Core +{ + [AppStartup(70)] + public class WeChatStartup : AppStartup + { + public void ConfigureServices(IServiceCollection services) + { + services.AddSenparcWeixinServices(App.Configuration); + + } + + public void Configure(IApplicationBuilder app, IOptions senparcSetting, + IOptions senparcWeixinSetting) + { + IRegisterService register = RegisterService.Start(senparcSetting.Value) + .UseSenparcGlobal(); + register.UseSenparcGlobal(true); + + AccessTokenContainer.RegisterAsync(App.Configuration["SenparcWeixinSetting:WeixinAppId"], App.Configuration["SenparcWeixinSetting:WeixinAppSecret"]); + + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.WeChat.Core/Znyc.Dispatching.WeChat.Core.csproj b/src/Znyc.Dispatching.WeChat.Core/Znyc.Dispatching.WeChat.Core.csproj new file mode 100644 index 0000000..91f545d --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/Znyc.Dispatching.WeChat.Core.csproj @@ -0,0 +1,36 @@ + + + + net6.0 + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + + + + + + + + + + + diff --git a/src/Znyc.Dispatching.WeChat.Core/wechatsettings.Development.json b/src/Znyc.Dispatching.WeChat.Core/wechatsettings.Development.json new file mode 100644 index 0000000..5660f9f --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/wechatsettings.Development.json @@ -0,0 +1,18 @@ +{ + "SenparcSetting": { + "IsDebug": false, + "DefaultCacheNamespace": "", + "SenparcUnionAgentKey": "" + }, + "SenparcWeixinSetting": { + "IsDebug": false, + "WxOpenAppId": "wxa883c42a8db02847", + "WxOpenAppSecret": "4b9bd0910aab6c7b5266b07d5c17dba6", + "WxOpenToken": "", + "WxOpenEncodingAESKey": "", + "Token": "", + "EncodingAESKey": "", + "WeixinAppId": "wx07c574aca93ae8d9", + "WeixinAppSecret": "2d202f91258131f63565e11bdb065f6b" + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.WeChat.Core/wechatsettings.Production.json b/src/Znyc.Dispatching.WeChat.Core/wechatsettings.Production.json new file mode 100644 index 0000000..ded8ef4 --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/wechatsettings.Production.json @@ -0,0 +1,19 @@ +{ + "SenparcSetting": { + "IsDebug": false, + "DefaultCacheNamespace": "DefaultCache", + "SenparcUnionAgentKey": "#{SenparcUnionAgentKey}#" + }, + "SenparcWeixinSetting": { + "IsDebug": false, + "WxOpenAppId": "wxa883c42a8db02847", + "WxOpenAppSecret": "4b9bd0910aab6c7b5266b07d5c17dba6", + "WxOpenToken": "#{WxOpenToken}#", + "WxOpenEncodingAESKey": "#{WxOpenEncodingAESKey}#", + + "Token": "#{Token}#", + "EncodingAESKey": "#{EncodingAESKey}#", + "WeixinAppId": "wx07c574aca93ae8d9", + "WeixinAppSecret": "2d202f91258131f63565e11bdb065f6b" + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.WeChat.Core/wechatsettings.Staging.json b/src/Znyc.Dispatching.WeChat.Core/wechatsettings.Staging.json new file mode 100644 index 0000000..5660f9f --- /dev/null +++ b/src/Znyc.Dispatching.WeChat.Core/wechatsettings.Staging.json @@ -0,0 +1,18 @@ +{ + "SenparcSetting": { + "IsDebug": false, + "DefaultCacheNamespace": "", + "SenparcUnionAgentKey": "" + }, + "SenparcWeixinSetting": { + "IsDebug": false, + "WxOpenAppId": "wxa883c42a8db02847", + "WxOpenAppSecret": "4b9bd0910aab6c7b5266b07d5c17dba6", + "WxOpenToken": "", + "WxOpenEncodingAESKey": "", + "Token": "", + "EncodingAESKey": "", + "WeixinAppId": "wx07c574aca93ae8d9", + "WeixinAppSecret": "2d202f91258131f63565e11bdb065f6b" + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Core/Handlers/JwtHandler.cs b/src/Znyc.Dispatching.Web.Core/Handlers/JwtHandler.cs new file mode 100644 index 0000000..fd5d678 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Core/Handlers/JwtHandler.cs @@ -0,0 +1,96 @@ +using Furion; +using Furion.Authorization; +using Furion.DataEncryption; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using System.Threading.Tasks; +using Znyc.Dispatching.Application; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Extension; +using Znyc.Dispatching.Core.Options; + +namespace Znyc.Dispatching.Web.Core +{ + public class JwtHandler : AppAuthorizeHandler + { + /// + /// 重写 Handler 添加自动刷新 + /// + /// + /// + public override async Task HandleAsync(AuthorizationHandlerContext context) + { + // 自动刷新Token + if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext(), + App.GetOptions().ExpiredTime, + App.GetOptions().ExpiredTime)) + { + await AuthorizeHandleAsync(context); + } + else + { + context.Fail(); // 授权失败 + DefaultHttpContext currentHttpContext = context.GetCurrentHttpContext(); + if (currentHttpContext == null) + { + return; + } + + currentHttpContext.SignoutToSwagger(); + } + } + + /// + /// 授权判断逻辑,授权通过返回 true,否则返回 false + /// + /// + /// + /// + public override async Task PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext) + { + // 此处已经自动验证 Jwt Token的有效性了,无需手动验证 + return await CheckAuthorzieAsync(httpContext); + } + + + /// + /// 检查权限 + /// + /// + /// + private static async Task CheckAuthorzieAsync(DefaultHttpContext httpContext) + { + IUserManager _userManager = App.GetService(); + ICacheService _cacheService = App.GetService(); + //验证jwt有效期中是否被强制下线 + var token = await _cacheService.GetTokenAsync(_userManager.UserId); + if (token.IsNull()) + { + return false; + } + return true; + + #region 权限验证(暂时屏蔽) + + + // // 路由名称 + // string routeName = httpContext.Request.Path.Value.Substring(1).Replace("/", ":"); + // // 默认路由(获取登录用户信息) + // List defalutRoute = new List() + // { + // "Login" + // }; + + // if (defalutRoute.Contains(routeName)) + // { + // return true; + // } + // //获取用户权限集合 + // List permissionList = await App.GetService().GetLoginPermissionList(.UserId); + //// 检查授权 + // return permissionList.Contains(routeName); + + #endregion 权限验证(暂时屏蔽) + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Core/Startup.cs b/src/Znyc.Dispatching.Web.Core/Startup.cs new file mode 100644 index 0000000..9fc6292 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Core/Startup.cs @@ -0,0 +1,96 @@ +using Furion; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Yitter.IdGenerator; +using Znyc.Dispatching.Core; +using Znyc.Dispatching.Core.Cache; +using Znyc.Dispatching.Core.Options; +using Znyc.Dispatching.Web.Core; + +namespace Znyc.Dispatching.WeChat.Core +{ + [AppStartup(100)] + public class Startup : AppStartup + { + public void ConfigureServices(IServiceCollection services) + { + services.AddConfigurableOptions(); + services.AddJwt(enableGlobalAuthorize: true); + services.AddCorsAccessor(); + services.AddRemoteRequest(); + services.AddConfigurableOptions(); + + + services.AddControllersWithViews() + .AddNewtonsoftJson(options => + { + // 首字母小写(驼峰样式) + options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); + // 时间格式化 + options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; + // 忽略循环引用 + options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + // 忽略空值 + // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; + }) + //.AddMvcFilter() + .AddInjectWithUnifyResult(); + // .AddDataValidation(); + + services.AddRemoteRequest(); + + services.AddViewEngine(); + + services.AddSignalR(); + + services.AddConfigurableOptions(); + //配置微信 + services.AddConfigurableOptions(); + //配置短信 + services.AddConfigurableOptions(); + + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseHttpsRedirection(); + + app.UseStaticFiles(); + + //app.UseSerilogRequestLogging(); + + app.UseRouting(); + + app.UseCorsAccessor(); + + app.UseAuthentication(); + + app.UseAuthorization(); + + app.UseInject(string.Empty); + + app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); + + // 设置雪花Id的workerId,确保每个实例workerId都应不同 + var workerId = ushort.Parse(App.Configuration["SnowId:WorkerId"] ?? "1"); + YitIdHelper.SetIdGenerator(new IdGeneratorOptions { WorkerId = workerId }); + + + + + // 事件总线,订阅服务 + //app.ConfigureEventBus(); + + + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Core/Znyc.Dispatching.WeChat.Core.xml b/src/Znyc.Dispatching.Web.Core/Znyc.Dispatching.WeChat.Core.xml new file mode 100644 index 0000000..4cd86e0 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Core/Znyc.Dispatching.WeChat.Core.xml @@ -0,0 +1,30 @@ + + + + Znyc.Dispatching.Web.Core + + + + + 重写 Handler 添加自动刷新 + + + + + + + 授权判断逻辑,授权通过返回 true,否则返回 false + + + + + + + + 检查权限 + + + + + + diff --git a/src/Znyc.Dispatching.Web.Core/Znyc.Dispatching.Web.Core.csproj b/src/Znyc.Dispatching.Web.Core/Znyc.Dispatching.Web.Core.csproj new file mode 100644 index 0000000..6c8627c --- /dev/null +++ b/src/Znyc.Dispatching.Web.Core/Znyc.Dispatching.Web.Core.csproj @@ -0,0 +1,19 @@ + + + + net6.0 + 1701;1702;1591 + Znyc.Dispatching.WeChat.Core.xml + + + + + + + + + + + + + diff --git a/src/Znyc.Dispatching.Web.Core/Znyc.Dispatching.Web.Core.xml b/src/Znyc.Dispatching.Web.Core/Znyc.Dispatching.Web.Core.xml new file mode 100644 index 0000000..461c5fc --- /dev/null +++ b/src/Znyc.Dispatching.Web.Core/Znyc.Dispatching.Web.Core.xml @@ -0,0 +1,34 @@ + + + + + Znyc.Dispatching.Web.Core + + + + + 重写 Handler 添加自动刷新 + + + + + + + 授权判断逻辑,授权通过返回 true,否则返回 false + + + + + + + + 检查权限 + + + + + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Entry/Program.cs b/src/Znyc.Dispatching.Web.Entry/Program.cs new file mode 100644 index 0000000..4cc81d2 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Entry/Program.cs @@ -0,0 +1,13 @@ +using NLog; +using NLog.Web; + +var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); + +var builder = WebApplication.CreateBuilder(args).Inject(); +builder.Logging.ClearProviders(); +builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Warning); +builder.Host.UseNLog(); +var app = builder.Build(); +app.Run(); + + diff --git a/src/Znyc.Dispatching.Web.Entry/Properties/PublishProfiles/FolderProfile.pubxml b/src/Znyc.Dispatching.Web.Entry/Properties/PublishProfiles/FolderProfile.pubxml new file mode 100644 index 0000000..040b013 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Entry/Properties/PublishProfiles/FolderProfile.pubxml @@ -0,0 +1,16 @@ + + + + + False + False + True + Release + Any CPU + FileSystem + bin\Release\net5.0\publish\ + FileSystem + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Entry/Properties/PublishProfiles/FolderProfile1.pubxml b/src/Znyc.Dispatching.Web.Entry/Properties/PublishProfiles/FolderProfile1.pubxml new file mode 100644 index 0000000..377dd20 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Entry/Properties/PublishProfiles/FolderProfile1.pubxml @@ -0,0 +1,16 @@ + + + + + False + False + True + Release + Any CPU + FileSystem + bin\Release\net6.0\publish\ + FileSystem + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Entry/Properties/launchSettings.json b/src/Znyc.Dispatching.Web.Entry/Properties/launchSettings.json new file mode 100644 index 0000000..577cd94 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Entry/Properties/launchSettings.json @@ -0,0 +1,36 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:53785", + "sslPort": 44342 + } + }, + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Znyc.Dispatching.Web.Entry": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": "true", + "applicationUrl": "http://localhost:80" + }, + "Docker": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", + "publishAllPorts": true, + "useSSL": true + } + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj b/src/Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj new file mode 100644 index 0000000..6073b6f --- /dev/null +++ b/src/Znyc.Dispatching.Web.Entry/Znyc.Dispatching.Web.Entry.csproj @@ -0,0 +1,52 @@ + + + + net6.0 + enable + Linux + + + + + + + + + + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + PreserveNewest + + + Always + + + + + cf45ded9-40d9-4078-a133-25f7f15d258e + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Entry/appsettings.Development.json b/src/Znyc.Dispatching.Web.Entry/appsettings.Development.json new file mode 100644 index 0000000..18be695 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Entry/appsettings.Development.json @@ -0,0 +1,89 @@ +{ + "AllowedHosts": "*", + "Upload": { + //ͷ + "avatar": { + //ϴ· D:/upload/admin/avatar + "uploadPath": "../upload/avatar", + //· + "requestPath": "/upload/avatar", + //ȡ· + "readPath": "https://znyc-images-1304677865.cos.ap-guangzhou.myqcloud.com/", + + //·ڸʽ yyyy/MM/dd + "dateTimeFormat": "", + //{û} + "format": "", + //ͼƬС 1M = 1 * 1024 * 1024 + "maxSize": 1048576, + //ϴ-1 + "limit": 1, + //ͼƬʽ + "contentType": [ "image/jpg", "image/png", "image/jpeg", "image/gif" ] + }, + //ĵͼƬ + "document": { + //ϴ· D:/upload/admin/document + "uploadPath": "../upload/document", + //· + "requestPath": "/images", + //·ڸʽ yyyy/MM/dd + "dateTimeFormat": "", + //{ĵ} + "format": "", + //ͼƬС 1M = 1 * 1024 * 1024 + "maxSize": 1048576, + //ϴ-1 + "limit": -1, + //ͼƬʽ + "contentType": [ "image/jpg", "image/png", "image/jpeg", "image/gif" ] + }, + + "secretId": "AKIDGSN2VjJkZ7pIYzcdo0zjDCKCnQpEhXbW", + "secretKey": "rQDI7fuoUyIEvLT5RWKqkUyGQJwBiU2P", + "bucket": "znyc-images-1304677865", + "region": "ap-guangzhou" + }, + "UploadInfo": { + "secretId": "AKIDGMBk7D3cuvf8KFtGMBj00iALFsEJ7dsq", + "secretKey": "i9IBn8Bzav0pMcbJkunPjmY3HsCF2Zom", + "bucket": "znyc-images-1304677865", + "region": "ap-guangzhou", + "allowPrefix": "a.jpg", + "durationSeconds": 1800, + "allowActions": [ + "name/cos:PutObject", + // ϴСϴ + "name/cos:PostObject", + // Ƭϴ + "name/cos:InitiateMultipartUpload", + "name/cos:ListMultipartUploads", + "name/cos:ListParts", + "name/cos:UploadPart", + "name/cos:CompleteMultipartUpload" + ] + }, + "RabbitMQ": { + "Enabled": false, + "Connection": "1.14.140.50", + "UserName": "znyc", + "Password": "eOmgADo3G", + "RetryCount": 3 + }, + "EventBus": { + "Enabled": false, + "SubscriptionClientName": "Dispatching" + }, + "Exceptionless": { + "ApiKey": "0V64pWS506bwhU73xqsXjznXfo23i8ClxLTDD0WE", + "ServerUrl": "http://42.194.147.251:5000" + }, + "Hangfire": { + "Login": "znyc", + "Password": "znyc2021" + + }, + "SnowId": { + "WorkerId": "1" // ȡֵΧ0~63,Ĭ1 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Entry/appsettings.Production.json b/src/Znyc.Dispatching.Web.Entry/appsettings.Production.json new file mode 100644 index 0000000..a133484 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Entry/appsettings.Production.json @@ -0,0 +1,93 @@ +{ + "AppSettings": { + "InjectSpecificationDocument": true + }, + "AllowedHosts": "*", + + "Upload": { + //ͷ + "avatar": { + //ϴ· D:/upload/admin/avatar + "uploadPath": "../upload/avatar", + //· + "requestPath": "/upload/avatar", + //ȡ· + "readPath": "https://znyc-images-1304677865.cos.ap-guangzhou.myqcloud.com/", + + //·ڸʽ yyyy/MM/dd + "dateTimeFormat": "", + //{û} + "format": "", + //ͼƬС 1M = 1 * 1024 * 1024 + "maxSize": 1048576, + //ϴ-1 + "limit": 1, + //ͼƬʽ + "contentType": [ "image/jpg", "image/png", "image/jpeg", "image/gif" ] + }, + //ĵͼƬ + "document": { + //ϴ· D:/upload/admin/document + "uploadPath": "../upload/document", + //· + "requestPath": "/images", + //·ڸʽ yyyy/MM/dd + "dateTimeFormat": "", + //{ĵ} + "format": "", + //ͼƬС 1M = 1 * 1024 * 1024 + "maxSize": 1048576, + //ϴ-1 + "limit": -1, + //ͼƬʽ + "contentType": [ "image/jpg", "image/png", "image/jpeg", "image/gif" ] + }, + + "secretId": "AKIDGSN2VjJkZ7pIYzcdo0zjDCKCnQpEhXbW", + "secretKey": "rQDI7fuoUyIEvLT5RWKqkUyGQJwBiU2P", + "bucket": "znyc-images-1304677865", + "region": "ap-guangzhou" + }, + "UploadInfo": { + "secretId": "AKIDGMBk7D3cuvf8KFtGMBj00iALFsEJ7dsq", + "secretKey": "i9IBn8Bzav0pMcbJkunPjmY3HsCF2Zom", + "bucket": "znyc-images-1304677865", + "region": "ap-guangzhou", + "allowPrefix": "a.jpg", + "durationSeconds": 1800, + "allowActions": [ + "name/cos:PutObject", + // ϴСϴ + "name/cos:PostObject", + // Ƭϴ + "name/cos:InitiateMultipartUpload", + "name/cos:ListMultipartUploads", + "name/cos:ListParts", + "name/cos:UploadPart", + "name/cos:CompleteMultipartUpload" + ] + }, + "RabbitMQ": { + "Enabled": false, + "Connection": "1.14.140.50", + "UserName": "znyc", + "Password": "eOmgADo3G", + "RetryCount": 3 + }, + "EventBus": { + "Enabled": false, + "SubscriptionClientName": "Dispatching" + }, + "Exceptionless": { + "ApiKey": "Z74DxFmICy9ZLGmIBOtWkWxNvWbUlmZSS1PkH7hb", + "ServerUrl": "http://1.14.140.50:5000" + }, + "Hangfire": { + "Login": "root", + "Password": "jxdieJh/l" + + }, + "SnowId": { + "WorkerId": "1" // ȡֵΧ0~63,Ĭ1 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Entry/appsettings.Staging.json b/src/Znyc.Dispatching.Web.Entry/appsettings.Staging.json new file mode 100644 index 0000000..4737a10 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Entry/appsettings.Staging.json @@ -0,0 +1,89 @@ +{ + "AllowedHosts": "*", + "Upload": { + //ͷ + "avatar": { + //ϴ· D:/upload/admin/avatar + "uploadPath": "../upload/avatar", + //· + "requestPath": "/upload/avatar", + //ȡ· + "readPath": "https://znyc-images-1304677865.cos.ap-guangzhou.myqcloud.com/", + + //·ڸʽ yyyy/MM/dd + "dateTimeFormat": "", + //{û} + "format": "", + //ͼƬС 1M = 1 * 1024 * 1024 + "maxSize": 1048576, + //ϴ-1 + "limit": 1, + //ͼƬʽ + "contentType": [ "image/jpg", "image/png", "image/jpeg", "image/gif" ] + }, + //ĵͼƬ + "document": { + //ϴ· D:/upload/admin/document + "uploadPath": "../upload/document", + //· + "requestPath": "/images", + //·ڸʽ yyyy/MM/dd + "dateTimeFormat": "", + //{ĵ} + "format": "", + //ͼƬС 1M = 1 * 1024 * 1024 + "maxSize": 1048576, + //ϴ-1 + "limit": -1, + //ͼƬʽ + "contentType": [ "image/jpg", "image/png", "image/jpeg", "image/gif" ] + }, + + "secretId": "AKIDGSN2VjJkZ7pIYzcdo0zjDCKCnQpEhXbW", + "secretKey": "rQDI7fuoUyIEvLT5RWKqkUyGQJwBiU2P", + "bucket": "znyc-images-1304677865", + "region": "ap-guangzhou" + }, + "UploadInfo": { + "secretId": "AKIDGMBk7D3cuvf8KFtGMBj00iALFsEJ7dsq", + "secretKey": "i9IBn8Bzav0pMcbJkunPjmY3HsCF2Zom", + "bucket": "znyc-images-1304677865", + "region": "ap-guangzhou", + "allowPrefix": "a.jpg", + "durationSeconds": 1800, + "allowActions": [ + "name/cos:PutObject", + // ϴСϴ + "name/cos:PostObject", + // Ƭϴ + "name/cos:InitiateMultipartUpload", + "name/cos:ListMultipartUploads", + "name/cos:ListParts", + "name/cos:UploadPart", + "name/cos:CompleteMultipartUpload" + ] + }, + "RabbitMQ": { + "Enabled": false, + "Connection": "1.14.140.50", + "UserName": "znyc", + "Password": "eOmgADo3G", + "RetryCount": 3 + }, + "EventBus": { + "Enabled": false, + "SubscriptionClientName": "Dispatching" + }, + "Exceptionless": { + "ApiKey": "0V64pWS506bwhU73xqsXjznXfo23i8ClxLTDD0WE", + "ServerUrl": "http://42.194.147.251:5000" + }, + "Hangfire": { + "Login": "faker", + "Password": "faker2021" + + }, + "SnowId": { + "WorkerId": "1" // ȡֵΧ0~63,Ĭ1 + } +} \ No newline at end of file diff --git a/src/Znyc.Dispatching.Web.Entry/nlog.config b/src/Znyc.Dispatching.Web.Entry/nlog.config new file mode 100644 index 0000000..e6acb50 --- /dev/null +++ b/src/Znyc.Dispatching.Web.Entry/nlog.config @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Znyc.Dispatching.sln b/src/Znyc.Dispatching.sln new file mode 100644 index 0000000..7ae6a32 --- /dev/null +++ b/src/Znyc.Dispatching.sln @@ -0,0 +1,85 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31825.309 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.Application", "Znyc.Dispatching.Application\Znyc.Dispatching.Application.csproj", "{AB699EE9-43A8-46F2-A855-04A26DE63372}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.EntityFramework.Core", "Znyc.Dispatching.EntityFramework.Core\Znyc.Dispatching.EntityFramework.Core.csproj", "{4BD77E5C-138D-4F2D-B709-F9020F306AF3}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.Web.Core", "Znyc.Dispatching.Web.Core\Znyc.Dispatching.Web.Core.csproj", "{9D14BB78-DA2A-4040-B9DB-5A515B599181}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.Core", "Znyc.Dispatching.Core\Znyc.Dispatching.Core.csproj", "{4FB30091-15C7-4FD9-AB7D-266814F360F5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.Database.Migrations", "Znyc.Dispatching.Database.Migrations\Znyc.Dispatching.Database.Migrations.csproj", "{EA769D36-9D55-47A6-945F-1687EA95179F}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.Web.Entry", "Znyc.Dispatching.Web.Entry\Znyc.Dispatching.Web.Entry.csproj", "{C8D99F52-EDC7-411F-8300-6DB14BF59E8C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.Tests", "Znyc.Dispatchimg.Test\Znyc.Dispatching.Tests.csproj", "{A712DF7E-1D6A-4594-BE81-360608861826}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.MongoDb.Repository", "Znyc.Dispatching.MongoDb.Repository\Znyc.Dispatching.MongoDb.Repository.csproj", "{61B8F8EB-3CA7-4B49-A952-538FE1FBBF9C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.WeChat.Core", "Znyc.Dispatching.WeChat.Core\Znyc.Dispatching.WeChat.Core.csproj", "{6807B4D4-1AF4-45C1-A070-51FF81F18BAD}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.Common", "Znyc.Dispatching.Common\Znyc.Dispatching.Common.csproj", "{869240E7-2C85-4EF6-A42E-78A7DA34351D}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Znyc.Dispatching.Tasks", "Znyc.Dispatching.Tasks\Znyc.Dispatching.Tasks.csproj", "{F947FB16-40F3-42B3-921D-49B83AC82886}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AB699EE9-43A8-46F2-A855-04A26DE63372}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB699EE9-43A8-46F2-A855-04A26DE63372}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB699EE9-43A8-46F2-A855-04A26DE63372}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB699EE9-43A8-46F2-A855-04A26DE63372}.Release|Any CPU.Build.0 = Release|Any CPU + {4BD77E5C-138D-4F2D-B709-F9020F306AF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4BD77E5C-138D-4F2D-B709-F9020F306AF3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4BD77E5C-138D-4F2D-B709-F9020F306AF3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4BD77E5C-138D-4F2D-B709-F9020F306AF3}.Release|Any CPU.Build.0 = Release|Any CPU + {9D14BB78-DA2A-4040-B9DB-5A515B599181}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9D14BB78-DA2A-4040-B9DB-5A515B599181}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9D14BB78-DA2A-4040-B9DB-5A515B599181}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9D14BB78-DA2A-4040-B9DB-5A515B599181}.Release|Any CPU.Build.0 = Release|Any CPU + {4FB30091-15C7-4FD9-AB7D-266814F360F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4FB30091-15C7-4FD9-AB7D-266814F360F5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4FB30091-15C7-4FD9-AB7D-266814F360F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4FB30091-15C7-4FD9-AB7D-266814F360F5}.Release|Any CPU.Build.0 = Release|Any CPU + {EA769D36-9D55-47A6-945F-1687EA95179F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EA769D36-9D55-47A6-945F-1687EA95179F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EA769D36-9D55-47A6-945F-1687EA95179F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EA769D36-9D55-47A6-945F-1687EA95179F}.Release|Any CPU.Build.0 = Release|Any CPU + {C8D99F52-EDC7-411F-8300-6DB14BF59E8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8D99F52-EDC7-411F-8300-6DB14BF59E8C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8D99F52-EDC7-411F-8300-6DB14BF59E8C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C8D99F52-EDC7-411F-8300-6DB14BF59E8C}.Release|Any CPU.Build.0 = Release|Any CPU + {A712DF7E-1D6A-4594-BE81-360608861826}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A712DF7E-1D6A-4594-BE81-360608861826}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A712DF7E-1D6A-4594-BE81-360608861826}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A712DF7E-1D6A-4594-BE81-360608861826}.Release|Any CPU.Build.0 = Release|Any CPU + {61B8F8EB-3CA7-4B49-A952-538FE1FBBF9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {61B8F8EB-3CA7-4B49-A952-538FE1FBBF9C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {61B8F8EB-3CA7-4B49-A952-538FE1FBBF9C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {61B8F8EB-3CA7-4B49-A952-538FE1FBBF9C}.Release|Any CPU.Build.0 = Release|Any CPU + {6807B4D4-1AF4-45C1-A070-51FF81F18BAD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6807B4D4-1AF4-45C1-A070-51FF81F18BAD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6807B4D4-1AF4-45C1-A070-51FF81F18BAD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6807B4D4-1AF4-45C1-A070-51FF81F18BAD}.Release|Any CPU.Build.0 = Release|Any CPU + {869240E7-2C85-4EF6-A42E-78A7DA34351D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {869240E7-2C85-4EF6-A42E-78A7DA34351D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {869240E7-2C85-4EF6-A42E-78A7DA34351D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {869240E7-2C85-4EF6-A42E-78A7DA34351D}.Release|Any CPU.Build.0 = Release|Any CPU + {F947FB16-40F3-42B3-921D-49B83AC82886}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F947FB16-40F3-42B3-921D-49B83AC82886}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F947FB16-40F3-42B3-921D-49B83AC82886}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F947FB16-40F3-42B3-921D-49B83AC82886}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B2073C2C-0FD3-452B-8047-8134D68E12CE} + EndGlobalSection +EndGlobal