diff --git a/.gitignore b/.gitignore index 48f9436c..0a19b884 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ logs/ target/ .txlcn/ +nacos/ *.iml -*.versionsBackup \ No newline at end of file +*.versionsBackup diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..7b016a89 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.compile.nullAnalysis.mode": "automatic" +} \ No newline at end of file diff --git a/README.md b/README.md index 3c300e09..01f56e4b 100644 --- a/README.md +++ b/README.md @@ -172,4 +172,5 @@ central-platform -- 父项目,公共依赖 1.全网唯一使用JavaAgent实现Http、MQ、Job全链路灰度 -2.全网唯一支持JavaAgent接入Sentinel \ No newline at end of file +2.全网唯一支持JavaAgent接入Sentinel + diff --git a/hs_err_pid25368.log b/hs_err_pid25368.log new file mode 100644 index 00000000..8548f2ad --- /dev/null +++ b/hs_err_pid25368.log @@ -0,0 +1,996 @@ +# +# There is insufficient memory for the Java Runtime Environment to continue. +# Native memory allocation (mmap) failed to map 734003200 bytes for G1 virtual space +# Possible reasons: +# The system is out of physical RAM or swap space +# The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap +# Possible solutions: +# Reduce memory load on the system +# Increase physical memory or swap space +# Check if swap backing store is full +# Decrease Java heap size (-Xmx/-Xms) +# Decrease number of Java threads +# Decrease Java thread stack sizes (-Xss) +# Set larger code cache with -XX:ReservedCodeCacheSize= +# JVM is running with Zero Based Compressed Oops mode in which the Java heap is +# placed in the first 32GB address space. The Java Heap base address is the +# maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress +# to set the Java Heap base and to place the Java Heap above 32GB virtual address. +# This output file may be truncated or incomplete. +# +# Out of Memory Error (os_windows.cpp:3548), pid=25368, tid=16648 +# +# JRE version: Java(TM) SE Runtime Environment (17.0.13+10) (build 17.0.13+10-LTS-268) +# Java VM: Java HotSpot(TM) 64-Bit Server VM (17.0.13+10-LTS-268, mixed mode, sharing, tiered, compressed oops, compressed class ptrs, g1 gc, windows-amd64) +# No core dump will be written. Minidumps are not enabled by default on client versions of Windows +# + +--------------- S U M M A R Y ------------ + +Command Line: -Dmaven.multiModuleProjectDirectory=E:\Idea-project\ikingtec-new6.0\microservices-platform -Djansi.passthrough=true -Dmaven.home=D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\plugins\maven\lib\maven3 -Dclassworlds.conf=D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\plugins\maven\lib\maven3\bin\m2.conf -Dmaven.ext.class.path=D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\plugins\maven\lib\maven-event-listener.jar -javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\lib\idea_rt.jar=58940:D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\bin -Dfile.encoding=UTF-8 org.codehaus.classworlds.Launcher -Didea.version=2024.3.1 -T 8 -s D:\maven\apache-maven-3.5.2\conf\settings.xml package + +Host: Intel(R) Core(TM) i7-9700F CPU @ 3.00GHz, 8 cores, 31G, Windows 10 , 64 bit Build 19041 (10.0.19041.5198) +Time: Sun Jan 5 03:07:02 2025 Windows 10 , 64 bit Build 19041 (10.0.19041.5198) elapsed time: 21.807413 seconds (0d 0h 0m 21s) + +--------------- T H R E A D --------------- + +Current thread (0x000002577ec0ce20): VMThread "VM Thread" [stack: 0x000000a0c9200000,0x000000a0c9300000] [id=16648] + +Stack: [0x000000a0c9200000,0x000000a0c9300000] +Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code) +V [jvm.dll+0x67a23a] +V [jvm.dll+0x7da96d] +V [jvm.dll+0x7dc2b3] +V [jvm.dll+0x7dc923] +V [jvm.dll+0x2450ef] +V [jvm.dll+0x677279] +V [jvm.dll+0x66bf22] +V [jvm.dll+0x302006] +V [jvm.dll+0x3095a6] +V [jvm.dll+0x359e9e] +V [jvm.dll+0x35a0cf] +V [jvm.dll+0x2d90d8] +V [jvm.dll+0x2d750d] +V [jvm.dll+0x2d6b5c] +V [jvm.dll+0x31a6bb] +V [jvm.dll+0x7e121b] +V [jvm.dll+0x7e1f54] +V [jvm.dll+0x7e246d] +V [jvm.dll+0x7e2844] +V [jvm.dll+0x7e2910] +V [jvm.dll+0x78af1a] +V [jvm.dll+0x679125] +C [ucrtbase.dll+0x21bb2] +C [KERNEL32.DLL+0x17374] +C [ntdll.dll+0x4cc91] + +VM_Operation (0x000000a0caffda70): G1CollectForAllocation, mode: safepoint, requested by thread 0x0000025747e837f0 + + +--------------- P R O C E S S --------------- + +Threads class SMR info: +_java_thread_list=0x0000025783920dc0, length=24, elements={ +0x00000257543ff050, 0x000002577ec11c60, 0x000002577ec127f0, 0x000002577ec2c960, +0x000002577ec2f240, 0x000002577ec2fb10, 0x000002577ec31f60, 0x000002577ec32b60, +0x000002577ec34090, 0x000002577ec3aa20, 0x000002577f560090, 0x000002577f6d0220, +0x000002577f6d0700, 0x00000257472e95c0, 0x00000257477e9500, 0x0000025747e80550, +0x0000025747e828c0, 0x0000025747e82dd0, 0x0000025747e832e0, 0x0000025747e80a60, +0x0000025747e80f70, 0x0000025747e837f0, 0x0000025747e83d00, 0x0000025747e81990 +} + +Java Threads: ( => current thread ) + 0x00000257543ff050 JavaThread "main" [_thread_blocked, id=16164, stack(0x000000a0c8c00000,0x000000a0c8d00000)] + 0x000002577ec11c60 JavaThread "Reference Handler" daemon [_thread_blocked, id=30264, stack(0x000000a0c9300000,0x000000a0c9400000)] + 0x000002577ec127f0 JavaThread "Finalizer" daemon [_thread_blocked, id=25264, stack(0x000000a0c9400000,0x000000a0c9500000)] + 0x000002577ec2c960 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=28952, stack(0x000000a0c9500000,0x000000a0c9600000)] + 0x000002577ec2f240 JavaThread "Attach Listener" daemon [_thread_blocked, id=22620, stack(0x000000a0c9600000,0x000000a0c9700000)] + 0x000002577ec2fb10 JavaThread "Service Thread" daemon [_thread_blocked, id=19780, stack(0x000000a0c9700000,0x000000a0c9800000)] + 0x000002577ec31f60 JavaThread "Monitor Deflation Thread" daemon [_thread_blocked, id=16724, stack(0x000000a0c9800000,0x000000a0c9900000)] + 0x000002577ec32b60 JavaThread "C2 CompilerThread0" daemon [_thread_blocked, id=18424, stack(0x000000a0c9900000,0x000000a0c9a00000)] + 0x000002577ec34090 JavaThread "C1 CompilerThread0" daemon [_thread_blocked, id=26280, stack(0x000000a0c9a00000,0x000000a0c9b00000)] + 0x000002577ec3aa20 JavaThread "Sweeper thread" daemon [_thread_blocked, id=18348, stack(0x000000a0c9b00000,0x000000a0c9c00000)] + 0x000002577f560090 JavaThread "Common-Cleaner" daemon [_thread_blocked, id=31456, stack(0x000000a0c9c00000,0x000000a0c9d00000)] + 0x000002577f6d0220 JavaThread "Monitor Ctrl-Break" daemon [_thread_in_native, id=12312, stack(0x000000a0c9d00000,0x000000a0c9e00000)] + 0x000002577f6d0700 JavaThread "Notification Thread" daemon [_thread_blocked, id=27832, stack(0x000000a0c9e00000,0x000000a0c9f00000)] + 0x00000257472e95c0 JavaThread "C2 CompilerThread1" daemon [_thread_blocked, id=4900, stack(0x000000a0ca000000,0x000000a0ca100000)] + 0x00000257477e9500 JavaThread "C2 CompilerThread2" daemon [_thread_blocked, id=29180, stack(0x000000a0ca100000,0x000000a0ca200000)] + 0x0000025747e80550 JavaThread "Thread-1" daemon [_thread_blocked, id=25424, stack(0x000000a0ca900000,0x000000a0caa00000)] + 0x0000025747e828c0 JavaThread "BuilderThread 0" [_thread_blocked, id=30432, stack(0x000000a0caa00000,0x000000a0cab00000)] + 0x0000025747e82dd0 JavaThread "mvn-builder-user-center" [_thread_blocked, id=26920, stack(0x000000a0cab00000,0x000000a0cac00000)] + 0x0000025747e832e0 JavaThread "mvn-builder-device-center" [_thread_blocked, id=11224, stack(0x000000a0cac00000,0x000000a0cad00000)] + 0x0000025747e80a60 JavaThread "BuilderThread 3" [_thread_blocked, id=18428, stack(0x000000a0cad00000,0x000000a0cae00000)] + 0x0000025747e80f70 JavaThread "mvn-builder-search-server" [_thread_blocked, id=912, stack(0x000000a0cae00000,0x000000a0caf00000)] + 0x0000025747e837f0 JavaThread "mvn-builder-zlt-uaa" [_thread_blocked, id=19144, stack(0x000000a0caf00000,0x000000a0cb000000)] + 0x0000025747e83d00 JavaThread "mvn-builder-sc-gateway" [_thread_blocked, id=15892, stack(0x000000a0cb000000,0x000000a0cb100000)] + 0x0000025747e81990 JavaThread "mvn-builder-tourism-core" [_thread_blocked, id=11476, stack(0x000000a0cb100000,0x000000a0cb200000)] + +Other Threads: +=>0x000002577ec0ce20 VMThread "VM Thread" [stack: 0x000000a0c9200000,0x000000a0c9300000] [id=16648] + 0x000002577f73e060 WatcherThread [stack: 0x000000a0c9f00000,0x000000a0ca000000] [id=27448] + 0x000002575446c3e0 GCTaskThread "GC Thread#0" [stack: 0x000000a0c8d00000,0x000000a0c8e00000] [id=15572] + 0x00000257477e9a20 GCTaskThread "GC Thread#1" [stack: 0x000000a0ca200000,0x000000a0ca300000] [id=27424] + 0x0000025747647e60 GCTaskThread "GC Thread#2" [stack: 0x000000a0ca300000,0x000000a0ca400000] [id=27164] + 0x0000025747648120 GCTaskThread "GC Thread#3" [stack: 0x000000a0ca400000,0x000000a0ca500000] [id=27856] + 0x0000025747648bf0 GCTaskThread "GC Thread#4" [stack: 0x000000a0ca500000,0x000000a0ca600000] [id=24492] + 0x000002574775a1a0 GCTaskThread "GC Thread#5" [stack: 0x000000a0ca600000,0x000000a0ca700000] [id=22336] + 0x000002574775a460 GCTaskThread "GC Thread#6" [stack: 0x000000a0ca700000,0x000000a0ca800000] [id=23664] + 0x000002574775a720 GCTaskThread "GC Thread#7" [stack: 0x000000a0ca800000,0x000000a0ca900000] [id=3648] + 0x000002575447d0c0 ConcurrentGCThread "G1 Main Marker" [stack: 0x000000a0c8e00000,0x000000a0c8f00000] [id=30772] + 0x000002575447d8e0 ConcurrentGCThread "G1 Conc#0" [stack: 0x000000a0c8f00000,0x000000a0c9000000] [id=21488] + 0x00000257498e01e0 ConcurrentGCThread "G1 Conc#1" [stack: 0x000000a0cb200000,0x000000a0cb300000] [id=27744] + 0x00000257544ae530 ConcurrentGCThread "G1 Refine#0" [stack: 0x000000a0c9000000,0x000000a0c9100000] [id=27880] + 0x0000025749319780 ConcurrentGCThread "G1 Refine#1" [stack: 0x000000a0cb300000,0x000000a0cb400000] [id=668] + 0x000002574858b650 ConcurrentGCThread "G1 Refine#2" [stack: 0x000000a0cb400000,0x000000a0cb500000] [id=31388] + 0x000002574858b940 ConcurrentGCThread "G1 Refine#3" [stack: 0x000000a0cb500000,0x000000a0cb600000] [id=3292] + 0x000002574b98f880 ConcurrentGCThread "G1 Refine#4" [stack: 0x000000a0cb600000,0x000000a0cb700000] [id=30844] + 0x0000025750ddf500 ConcurrentGCThread "G1 Refine#5" [stack: 0x000000a0cb700000,0x000000a0cb800000] [id=18084] + 0x000002577eb45030 ConcurrentGCThread "G1 Service" [stack: 0x000000a0c9100000,0x000000a0c9200000] [id=26648] + +Threads with active compile tasks: +C2 CompilerThread0 21840 20058 4 lombok.core.AST::buildWithField (21 bytes) +C2 CompilerThread1 21840 20070 ! 4 lombok.javac.JavacAST::drill (146 bytes) +C2 CompilerThread2 21840 20059 ! 4 lombok.core.AST::buildWithField0 (121 bytes) + +VM state: at safepoint (normal execution) + +VM Mutex/Monitor currently owned by a thread: ([mutex/lock_event]) +[0x00000257543fc490] Threads_lock - owner thread: 0x000002577ec0ce20 +[0x00000257543fb4d0] Heap_lock - owner thread: 0x0000025747e837f0 + +Heap address: 0x0000000601000000, size: 8176 MB, Compressed Oops mode: Zero based, Oop shift amount: 3 + +CDS archive(s) mapped at: [0x0000025702000000-0x0000025702bd0000-0x0000025702bd0000), size 12386304, SharedBaseAddress: 0x0000025702000000, ArchiveRelocationMode: 1. +Compressed class space mapped at: 0x0000025703000000-0x0000025743000000, reserved size: 1073741824 +Narrow klass base: 0x0000025702000000, Narrow klass shift: 0, Narrow klass range: 0x100000000 + +GC Precious Log: + CPUs: 8 total, 8 available + Memory: 32701M + Large Page Support: Disabled + NUMA Support: Disabled + Compressed Oops: Enabled (Zero based) + Heap Region Size: 4M + Heap Min Capacity: 8M + Heap Initial Capacity: 512M + Heap Max Capacity: 8176M + Pre-touch: Disabled + Parallel Workers: 8 + Concurrent Workers: 2 + Concurrent Refinement Workers: 8 + Periodic GC: Disabled + +Heap: + garbage-first heap total 1400832K, used 464510K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 2 young (8192K), 2 survivors (8192K) + Metaspace used 49364K, committed 56640K, reserved 1114112K + class space used 5435K, committed 7168K, reserved 1048576K + +Heap Regions: E=young(eden), S=young(survivor), O=old, HS=humongous(starts), HC=humongous(continues), CS=collection set, F=free, OA=open archive, CA=closed archive, TAMS=top-at-mark-start (previous, next) +| 0|0x0000000601000000, 0x0000000601400000, 0x0000000601400000|100%| O| |TAMS 0x0000000601400000, 0x0000000601000000| Untracked +| 1|0x0000000601400000, 0x0000000601800000, 0x0000000601800000|100%| O| |TAMS 0x0000000601800000, 0x0000000601400000| Untracked +| 2|0x0000000601800000, 0x0000000601c00000, 0x0000000601c00000|100%| O| |TAMS 0x0000000601c00000, 0x0000000601800000| Untracked +| 3|0x0000000601c00000, 0x0000000602000000, 0x0000000602000000|100%| O| |TAMS 0x0000000602000000, 0x0000000601c00000| Untracked +| 4|0x0000000602000000, 0x0000000602400000, 0x0000000602400000|100%| O| |TAMS 0x0000000602400000, 0x0000000602000000| Untracked +| 5|0x0000000602400000, 0x0000000602800000, 0x0000000602800000|100%| O| |TAMS 0x0000000602800000, 0x0000000602400000| Untracked +| 6|0x0000000602800000, 0x0000000602c00000, 0x0000000602c00000|100%| O| |TAMS 0x0000000602800000, 0x0000000602800000| Untracked +| 7|0x0000000602c00000, 0x0000000603000000, 0x0000000603000000|100%| O| |TAMS 0x0000000603000000, 0x0000000602c00000| Untracked +| 8|0x0000000603000000, 0x0000000603400000, 0x0000000603400000|100%| O| |TAMS 0x0000000603400000, 0x0000000603000000| Untracked +| 9|0x0000000603400000, 0x0000000603800000, 0x0000000603800000|100%| O| |TAMS 0x0000000603800000, 0x0000000603400000| Untracked +| 10|0x0000000603800000, 0x0000000603c00000, 0x0000000603c00000|100%| O| |TAMS 0x0000000603c00000, 0x0000000603800000| Untracked +| 11|0x0000000603c00000, 0x0000000604000000, 0x0000000604000000|100%| O| |TAMS 0x0000000604000000, 0x0000000603c00000| Untracked +| 12|0x0000000604000000, 0x0000000604400000, 0x0000000604400000|100%| O| |TAMS 0x0000000604000000, 0x0000000604000000| Untracked +| 13|0x0000000604400000, 0x0000000604671c00, 0x0000000604800000| 61%| O| |TAMS 0x0000000604400000, 0x0000000604400000| Untracked +| 14|0x0000000604800000, 0x0000000604800000, 0x0000000604c00000| 0%| F| |TAMS 0x0000000604800000, 0x0000000604800000| Untracked +| 15|0x0000000604c00000, 0x0000000605000000, 0x0000000605000000|100%| O| |TAMS 0x0000000605000000, 0x0000000604c00000| Untracked +| 16|0x0000000605000000, 0x0000000605000000, 0x0000000605400000| 0%| F| |TAMS 0x0000000605000000, 0x0000000605000000| Untracked +| 17|0x0000000605400000, 0x0000000605400000, 0x0000000605800000| 0%| F| |TAMS 0x0000000605400000, 0x0000000605400000| Untracked +| 18|0x0000000605800000, 0x0000000605800000, 0x0000000605c00000| 0%| F| |TAMS 0x0000000605800000, 0x0000000605800000| Untracked +| 19|0x0000000605c00000, 0x0000000605c00000, 0x0000000606000000| 0%| F| |TAMS 0x0000000605c00000, 0x0000000605c00000| Untracked +| 20|0x0000000606000000, 0x0000000606000000, 0x0000000606400000| 0%| F| |TAMS 0x0000000606000000, 0x0000000606000000| Untracked +| 21|0x0000000606400000, 0x0000000606400000, 0x0000000606800000| 0%| F| |TAMS 0x0000000606400000, 0x0000000606400000| Untracked +| 22|0x0000000606800000, 0x0000000606c00000, 0x0000000606c00000|100%| O| |TAMS 0x0000000606c00000, 0x0000000606800000| Complete +| 23|0x0000000606c00000, 0x0000000606c00000, 0x0000000607000000| 0%| F| |TAMS 0x0000000606c00000, 0x0000000606c00000| Untracked +| 24|0x0000000607000000, 0x0000000607000000, 0x0000000607400000| 0%| F| |TAMS 0x0000000607000000, 0x0000000607000000| Untracked +| 25|0x0000000607400000, 0x0000000607400000, 0x0000000607800000| 0%| F| |TAMS 0x0000000607400000, 0x0000000607400000| Untracked +| 26|0x0000000607800000, 0x0000000607c00000, 0x0000000607c00000|100%| O| |TAMS 0x0000000607c00000, 0x0000000607800000| Complete +| 27|0x0000000607c00000, 0x0000000607c00000, 0x0000000608000000| 0%| F| |TAMS 0x0000000607c00000, 0x0000000607c00000| Untracked +| 28|0x0000000608000000, 0x0000000608400000, 0x0000000608400000|100%| O| |TAMS 0x0000000608400000, 0x0000000608000000| Complete +| 29|0x0000000608400000, 0x0000000608800000, 0x0000000608800000|100%| O| |TAMS 0x0000000608800000, 0x0000000608400000| Complete +| 30|0x0000000608800000, 0x0000000608c00000, 0x0000000608c00000|100%| O| |TAMS 0x0000000608c00000, 0x0000000608800000| Untracked +| 31|0x0000000608c00000, 0x0000000609000000, 0x0000000609000000|100%| O| |TAMS 0x0000000609000000, 0x0000000608c00000| Complete +| 32|0x0000000609000000, 0x0000000609000000, 0x0000000609400000| 0%| F| |TAMS 0x0000000609000000, 0x0000000609000000| Untracked +| 33|0x0000000609400000, 0x0000000609400000, 0x0000000609800000| 0%| F| |TAMS 0x0000000609400000, 0x0000000609400000| Untracked +| 34|0x0000000609800000, 0x0000000609800000, 0x0000000609c00000| 0%| F| |TAMS 0x0000000609800000, 0x0000000609800000| Untracked +| 35|0x0000000609c00000, 0x0000000609c00000, 0x000000060a000000| 0%| F| |TAMS 0x0000000609c00000, 0x0000000609c00000| Untracked +| 36|0x000000060a000000, 0x000000060a400000, 0x000000060a400000|100%|HS| |TAMS 0x000000060a400000, 0x000000060a000000| Complete +| 37|0x000000060a400000, 0x000000060a800000, 0x000000060a800000|100%| O| |TAMS 0x000000060a800000, 0x000000060a400000| Complete +| 38|0x000000060a800000, 0x000000060a800000, 0x000000060ac00000| 0%| F| |TAMS 0x000000060a800000, 0x000000060a800000| Untracked +| 39|0x000000060ac00000, 0x000000060b000000, 0x000000060b000000|100%| O| |TAMS 0x000000060b000000, 0x000000060ac00000| Complete +| 40|0x000000060b000000, 0x000000060b400000, 0x000000060b400000|100%| O| |TAMS 0x000000060b400000, 0x000000060b000000| Complete +| 41|0x000000060b400000, 0x000000060b800000, 0x000000060b800000|100%| O| |TAMS 0x000000060b800000, 0x000000060b400000| Untracked +| 42|0x000000060b800000, 0x000000060bc00000, 0x000000060bc00000|100%| O| |TAMS 0x000000060bc00000, 0x000000060b800000| Complete +| 43|0x000000060bc00000, 0x000000060bc00000, 0x000000060c000000| 0%| F| |TAMS 0x000000060bc00000, 0x000000060bc00000| Untracked +| 44|0x000000060c000000, 0x000000060c000000, 0x000000060c400000| 0%| F| |TAMS 0x000000060c000000, 0x000000060c000000| Untracked +| 45|0x000000060c400000, 0x000000060c800000, 0x000000060c800000|100%| O| |TAMS 0x000000060c800000, 0x000000060c400000| Untracked +| 46|0x000000060c800000, 0x000000060cc00000, 0x000000060cc00000|100%| O| |TAMS 0x000000060cc00000, 0x000000060c800000| Untracked +| 47|0x000000060cc00000, 0x000000060cc00000, 0x000000060d000000| 0%| F| |TAMS 0x000000060cc00000, 0x000000060cc00000| Untracked +| 48|0x000000060d000000, 0x000000060d000000, 0x000000060d400000| 0%| F| |TAMS 0x000000060d000000, 0x000000060d000000| Untracked +| 49|0x000000060d400000, 0x000000060d400000, 0x000000060d800000| 0%| F| |TAMS 0x000000060d400000, 0x000000060d400000| Untracked +| 50|0x000000060d800000, 0x000000060d800000, 0x000000060dc00000| 0%| F| |TAMS 0x000000060d800000, 0x000000060d800000| Untracked +| 51|0x000000060dc00000, 0x000000060dc00000, 0x000000060e000000| 0%| F| |TAMS 0x000000060dc00000, 0x000000060dc00000| Untracked +| 52|0x000000060e000000, 0x000000060e000000, 0x000000060e400000| 0%| F| |TAMS 0x000000060e000000, 0x000000060e000000| Untracked +| 53|0x000000060e400000, 0x000000060e800000, 0x000000060e800000|100%| O| |TAMS 0x000000060e800000, 0x000000060e400000| Complete +| 54|0x000000060e800000, 0x000000060e800000, 0x000000060ec00000| 0%| F| |TAMS 0x000000060e800000, 0x000000060e800000| Untracked +| 55|0x000000060ec00000, 0x000000060ec00000, 0x000000060f000000| 0%| F| |TAMS 0x000000060ec00000, 0x000000060ec00000| Untracked +| 56|0x000000060f000000, 0x000000060f400000, 0x000000060f400000|100%| O| |TAMS 0x000000060f400000, 0x000000060f000000| Untracked +| 57|0x000000060f400000, 0x000000060f400000, 0x000000060f800000| 0%| F| |TAMS 0x000000060f400000, 0x000000060f400000| Untracked +| 58|0x000000060f800000, 0x000000060f800000, 0x000000060fc00000| 0%| F| |TAMS 0x000000060f800000, 0x000000060f800000| Untracked +| 59|0x000000060fc00000, 0x000000060fc00000, 0x0000000610000000| 0%| F| |TAMS 0x000000060fc00000, 0x000000060fc00000| Untracked +| 60|0x0000000610000000, 0x0000000610000000, 0x0000000610400000| 0%| F| |TAMS 0x0000000610000000, 0x0000000610000000| Untracked +| 61|0x0000000610400000, 0x0000000610400000, 0x0000000610800000| 0%| F| |TAMS 0x0000000610400000, 0x0000000610400000| Untracked +| 62|0x0000000610800000, 0x0000000610800000, 0x0000000610c00000| 0%| F| |TAMS 0x0000000610800000, 0x0000000610800000| Untracked +| 63|0x0000000610c00000, 0x0000000610c00000, 0x0000000611000000| 0%| F| |TAMS 0x0000000610c00000, 0x0000000610c00000| Untracked +| 64|0x0000000611000000, 0x0000000611000000, 0x0000000611400000| 0%| F| |TAMS 0x0000000611000000, 0x0000000611000000| Untracked +| 65|0x0000000611400000, 0x0000000611400000, 0x0000000611800000| 0%| F| |TAMS 0x0000000611400000, 0x0000000611400000| Untracked +| 66|0x0000000611800000, 0x0000000611800000, 0x0000000611c00000| 0%| F| |TAMS 0x0000000611800000, 0x0000000611800000| Untracked +| 67|0x0000000611c00000, 0x0000000611c00000, 0x0000000612000000| 0%| F| |TAMS 0x0000000611c00000, 0x0000000611c00000| Untracked +| 68|0x0000000612000000, 0x0000000612000000, 0x0000000612400000| 0%| F| |TAMS 0x0000000612000000, 0x0000000612000000| Untracked +| 69|0x0000000612400000, 0x0000000612800000, 0x0000000612800000|100%| O| |TAMS 0x0000000612800000, 0x0000000612400000| Complete +| 70|0x0000000612800000, 0x0000000612800000, 0x0000000612c00000| 0%| F| |TAMS 0x0000000612800000, 0x0000000612800000| Untracked +| 71|0x0000000612c00000, 0x0000000612c00000, 0x0000000613000000| 0%| F| |TAMS 0x0000000612c00000, 0x0000000612c00000| Untracked +| 72|0x0000000613000000, 0x0000000613000000, 0x0000000613400000| 0%| F| |TAMS 0x0000000613000000, 0x0000000613000000| Untracked +| 73|0x0000000613400000, 0x0000000613400000, 0x0000000613800000| 0%| F| |TAMS 0x0000000613400000, 0x0000000613400000| Untracked +| 74|0x0000000613800000, 0x0000000613800000, 0x0000000613c00000| 0%| F| |TAMS 0x0000000613800000, 0x0000000613800000| Untracked +| 75|0x0000000613c00000, 0x0000000613c00000, 0x0000000614000000| 0%| F| |TAMS 0x0000000613c00000, 0x0000000613c00000| Untracked +| 76|0x0000000614000000, 0x0000000614000000, 0x0000000614400000| 0%| F| |TAMS 0x0000000614000000, 0x0000000614000000| Untracked +| 77|0x0000000614400000, 0x0000000614400000, 0x0000000614800000| 0%| F| |TAMS 0x0000000614400000, 0x0000000614400000| Untracked +| 78|0x0000000614800000, 0x0000000614800000, 0x0000000614c00000| 0%| F| |TAMS 0x0000000614800000, 0x0000000614800000| Untracked +| 79|0x0000000614c00000, 0x0000000615000000, 0x0000000615000000|100%| O| |TAMS 0x0000000615000000, 0x0000000614c00000| Untracked +| 80|0x0000000615000000, 0x0000000615400000, 0x0000000615400000|100%| O| |TAMS 0x0000000615400000, 0x0000000615000000| Untracked +| 81|0x0000000615400000, 0x0000000615800000, 0x0000000615800000|100%| O| |TAMS 0x0000000615800000, 0x0000000615400000| Untracked +| 82|0x0000000615800000, 0x0000000615c00000, 0x0000000615c00000|100%| O| |TAMS 0x0000000615c00000, 0x0000000615800000| Untracked +| 83|0x0000000615c00000, 0x0000000616000000, 0x0000000616000000|100%| O| |TAMS 0x0000000616000000, 0x0000000615c00000| Complete +| 84|0x0000000616000000, 0x0000000616400000, 0x0000000616400000|100%| O| |TAMS 0x0000000616400000, 0x0000000616000000| Complete +| 85|0x0000000616400000, 0x0000000616800000, 0x0000000616800000|100%| O| |TAMS 0x0000000616800000, 0x0000000616400000| Complete +| 86|0x0000000616800000, 0x0000000616c00000, 0x0000000616c00000|100%| O| |TAMS 0x0000000616c00000, 0x0000000616800000| Complete +| 87|0x0000000616c00000, 0x0000000616c00000, 0x0000000617000000| 0%| F| |TAMS 0x0000000616c00000, 0x0000000616c00000| Untracked +| 88|0x0000000617000000, 0x0000000617400000, 0x0000000617400000|100%| O| |TAMS 0x0000000617400000, 0x0000000617000000| Untracked +| 89|0x0000000617400000, 0x0000000617800000, 0x0000000617800000|100%| O| |TAMS 0x0000000617800000, 0x0000000617400000| Untracked +| 90|0x0000000617800000, 0x0000000617c00000, 0x0000000617c00000|100%| O| |TAMS 0x0000000617c00000, 0x0000000617800000| Untracked +| 91|0x0000000617c00000, 0x0000000618000000, 0x0000000618000000|100%| O| |TAMS 0x0000000618000000, 0x0000000617c00000| Untracked +| 92|0x0000000618000000, 0x0000000618000000, 0x0000000618400000| 0%| F| |TAMS 0x0000000618000000, 0x0000000618000000| Untracked +| 93|0x0000000618400000, 0x0000000618400000, 0x0000000618800000| 0%| F| |TAMS 0x0000000618400000, 0x0000000618400000| Untracked +| 94|0x0000000618800000, 0x0000000618800000, 0x0000000618c00000| 0%| F| |TAMS 0x0000000618800000, 0x0000000618800000| Untracked +| 95|0x0000000618c00000, 0x0000000618c00000, 0x0000000619000000| 0%| F| |TAMS 0x0000000618c00000, 0x0000000618c00000| Untracked +| 96|0x0000000619000000, 0x0000000619400000, 0x0000000619400000|100%|HS| |TAMS 0x0000000619400000, 0x0000000619000000| Complete +| 97|0x0000000619400000, 0x0000000619800000, 0x0000000619800000|100%| O| |TAMS 0x0000000619800000, 0x0000000619400000| Complete +| 98|0x0000000619800000, 0x0000000619800000, 0x0000000619c00000| 0%| F| |TAMS 0x0000000619800000, 0x0000000619800000| Untracked +| 99|0x0000000619c00000, 0x0000000619c00000, 0x000000061a000000| 0%| F| |TAMS 0x0000000619c00000, 0x0000000619c00000| Untracked +| 100|0x000000061a000000, 0x000000061a000000, 0x000000061a400000| 0%| F| |TAMS 0x000000061a000000, 0x000000061a000000| Untracked +| 101|0x000000061a400000, 0x000000061a800000, 0x000000061a800000|100%| O| |TAMS 0x000000061a800000, 0x000000061a400000| Complete +| 102|0x000000061a800000, 0x000000061a800000, 0x000000061ac00000| 0%| F| |TAMS 0x000000061a800000, 0x000000061a800000| Untracked +| 103|0x000000061ac00000, 0x000000061ac00000, 0x000000061b000000| 0%| F| |TAMS 0x000000061ac00000, 0x000000061ac00000| Untracked +| 104|0x000000061b000000, 0x000000061b000000, 0x000000061b400000| 0%| F| |TAMS 0x000000061b000000, 0x000000061b000000| Untracked +| 105|0x000000061b400000, 0x000000061b800000, 0x000000061b800000|100%| O| |TAMS 0x000000061b800000, 0x000000061b400000| Complete +| 106|0x000000061b800000, 0x000000061bc00000, 0x000000061bc00000|100%| O| |TAMS 0x000000061bc00000, 0x000000061b800000| Untracked +| 107|0x000000061bc00000, 0x000000061c000000, 0x000000061c000000|100%| O| |TAMS 0x000000061c000000, 0x000000061bc00000| Untracked +| 108|0x000000061c000000, 0x000000061c000000, 0x000000061c400000| 0%| F| |TAMS 0x000000061c000000, 0x000000061c000000| Untracked +| 109|0x000000061c400000, 0x000000061c800000, 0x000000061c800000|100%| O| |TAMS 0x000000061c800000, 0x000000061c400000| Untracked +| 110|0x000000061c800000, 0x000000061cc00000, 0x000000061cc00000|100%| O| |TAMS 0x000000061cc00000, 0x000000061c800000| Untracked +| 111|0x000000061cc00000, 0x000000061cc00000, 0x000000061d000000| 0%| F| |TAMS 0x000000061cc00000, 0x000000061cc00000| Untracked +| 112|0x000000061d000000, 0x000000061d400000, 0x000000061d400000|100%| O| |TAMS 0x000000061d400000, 0x000000061d000000| Untracked +| 113|0x000000061d400000, 0x000000061d800000, 0x000000061d800000|100%| O| |TAMS 0x000000061d800000, 0x000000061d400000| Untracked +| 114|0x000000061d800000, 0x000000061d800000, 0x000000061dc00000| 0%| F| |TAMS 0x000000061d800000, 0x000000061d800000| Untracked +| 115|0x000000061dc00000, 0x000000061e000000, 0x000000061e000000|100%| O| |TAMS 0x000000061e000000, 0x000000061dc00000| Untracked +| 116|0x000000061e000000, 0x000000061e400000, 0x000000061e400000|100%| O| |TAMS 0x000000061e400000, 0x000000061e000000| Untracked +| 117|0x000000061e400000, 0x000000061e800000, 0x000000061e800000|100%| O| |TAMS 0x000000061e800000, 0x000000061e400000| Untracked +| 118|0x000000061e800000, 0x000000061ec00000, 0x000000061ec00000|100%| O| |TAMS 0x000000061ec00000, 0x000000061e800000| Untracked +| 119|0x000000061ec00000, 0x000000061f000000, 0x000000061f000000|100%| O| |TAMS 0x000000061f000000, 0x000000061ec00000| Untracked +| 120|0x000000061f000000, 0x000000061f400000, 0x000000061f400000|100%| O| |TAMS 0x000000061f400000, 0x000000061f000000| Untracked +| 121|0x000000061f400000, 0x000000061f800000, 0x000000061f800000|100%| O| |TAMS 0x000000061f800000, 0x000000061f400000| Untracked +| 122|0x000000061f800000, 0x000000061f800000, 0x000000061fc00000| 0%| F| |TAMS 0x000000061f800000, 0x000000061f800000| Untracked +| 123|0x000000061fc00000, 0x0000000620000000, 0x0000000620000000|100%| O| |TAMS 0x0000000620000000, 0x000000061fc00000| Complete +| 124|0x0000000620000000, 0x0000000620400000, 0x0000000620400000|100%| O| |TAMS 0x0000000620400000, 0x0000000620000000| Complete +| 125|0x0000000620400000, 0x0000000620800000, 0x0000000620800000|100%| O| |TAMS 0x0000000620800000, 0x0000000620400000| Untracked +| 126|0x0000000620800000, 0x0000000620c00000, 0x0000000620c00000|100%| O| |TAMS 0x0000000620c00000, 0x0000000620800000| Untracked +| 127|0x0000000620c00000, 0x0000000621000000, 0x0000000621000000|100%| O| |TAMS 0x0000000621000000, 0x0000000620c00000| Untracked +| 128|0x0000000621000000, 0x0000000621400000, 0x0000000621400000|100%| O| |TAMS 0x0000000621400000, 0x0000000621000000| Untracked +| 129|0x0000000621400000, 0x0000000621800000, 0x0000000621800000|100%| O| |TAMS 0x0000000621800000, 0x0000000621400000| Complete +| 130|0x0000000621800000, 0x0000000621c00000, 0x0000000621c00000|100%| O| |TAMS 0x0000000621c00000, 0x0000000621800000| Untracked +| 131|0x0000000621c00000, 0x0000000622000000, 0x0000000622000000|100%| O| |TAMS 0x0000000622000000, 0x0000000621c00000| Untracked +| 132|0x0000000622000000, 0x0000000622400000, 0x0000000622400000|100%| O| |TAMS 0x0000000622400000, 0x0000000622000000| Untracked +| 133|0x0000000622400000, 0x0000000622800000, 0x0000000622800000|100%| O| |TAMS 0x0000000622800000, 0x0000000622400000| Untracked +| 134|0x0000000622800000, 0x0000000622c00000, 0x0000000622c00000|100%| O| |TAMS 0x0000000622c00000, 0x0000000622800000| Complete +| 135|0x0000000622c00000, 0x0000000623000000, 0x0000000623000000|100%| O| |TAMS 0x0000000623000000, 0x0000000622c00000| Untracked +| 136|0x0000000623000000, 0x0000000623400000, 0x0000000623400000|100%| O| |TAMS 0x0000000623400000, 0x0000000623000000| Untracked +| 137|0x0000000623400000, 0x0000000623800000, 0x0000000623800000|100%| O| |TAMS 0x0000000623800000, 0x0000000623400000| Untracked +| 138|0x0000000623800000, 0x0000000623c00000, 0x0000000623c00000|100%| O| |TAMS 0x0000000623c00000, 0x0000000623800000| Untracked +| 139|0x0000000623c00000, 0x0000000624000000, 0x0000000624000000|100%| O| |TAMS 0x0000000624000000, 0x0000000623c00000| Complete +| 140|0x0000000624000000, 0x0000000624000000, 0x0000000624400000| 0%| F| |TAMS 0x0000000624000000, 0x0000000624000000| Untracked +| 141|0x0000000624400000, 0x0000000624400000, 0x0000000624800000| 0%| F| |TAMS 0x0000000624400000, 0x0000000624400000| Untracked +| 142|0x0000000624800000, 0x0000000624c00000, 0x0000000624c00000|100%| O| |TAMS 0x0000000624c00000, 0x0000000624800000| Complete +| 143|0x0000000624c00000, 0x0000000624c00000, 0x0000000625000000| 0%| F| |TAMS 0x0000000624c00000, 0x0000000624c00000| Untracked +| 144|0x0000000625000000, 0x0000000625400000, 0x0000000625400000|100%| O| |TAMS 0x0000000625400000, 0x0000000625000000| Untracked +| 145|0x0000000625400000, 0x0000000625800000, 0x0000000625800000|100%| O| |TAMS 0x0000000625800000, 0x0000000625400000| Untracked +| 146|0x0000000625800000, 0x0000000625c00000, 0x0000000625c00000|100%| O| |TAMS 0x0000000625c00000, 0x0000000625800000| Untracked +| 147|0x0000000625c00000, 0x0000000626000000, 0x0000000626000000|100%| O| |TAMS 0x0000000626000000, 0x0000000625c00000| Untracked +| 148|0x0000000626000000, 0x0000000626400000, 0x0000000626400000|100%| O| |TAMS 0x0000000626400000, 0x0000000626000000| Untracked +| 149|0x0000000626400000, 0x0000000626800000, 0x0000000626800000|100%| O| |TAMS 0x0000000626800000, 0x0000000626400000| Untracked +| 150|0x0000000626800000, 0x0000000626800000, 0x0000000626c00000| 0%| F| |TAMS 0x0000000626800000, 0x0000000626800000| Untracked +| 151|0x0000000626c00000, 0x0000000626c00000, 0x0000000627000000| 0%| F| |TAMS 0x0000000626c00000, 0x0000000626c00000| Untracked +| 152|0x0000000627000000, 0x0000000627400000, 0x0000000627400000|100%| O| |TAMS 0x0000000627400000, 0x0000000627000000| Untracked +| 153|0x0000000627400000, 0x0000000627800000, 0x0000000627800000|100%|HS| |TAMS 0x0000000627800000, 0x0000000627400000| Complete +| 154|0x0000000627800000, 0x0000000627c00000, 0x0000000627c00000|100%| O| |TAMS 0x0000000627836400, 0x0000000627800000| Untracked +| 155|0x0000000627c00000, 0x0000000628000000, 0x0000000628000000|100%|HS| |TAMS 0x0000000628000000, 0x0000000627c00000| Complete +| 156|0x0000000628000000, 0x0000000628400000, 0x0000000628400000|100%| O| |TAMS 0x0000000628000000, 0x0000000628000000| Untracked +| 157|0x0000000628400000, 0x0000000628800000, 0x0000000628800000|100%| O| |TAMS 0x0000000628400000, 0x0000000628400000| Untracked +| 158|0x0000000628800000, 0x0000000628c00000, 0x0000000628c00000|100%| O| |TAMS 0x0000000628800000, 0x0000000628800000| Untracked +| 159|0x0000000628c00000, 0x0000000629000000, 0x0000000629000000|100%| O| |TAMS 0x0000000628c00000, 0x0000000628c00000| Untracked +| 160|0x0000000629000000, 0x0000000629400000, 0x0000000629400000|100%| O| |TAMS 0x0000000629000000, 0x0000000629000000| Untracked +| 161|0x0000000629400000, 0x0000000629800000, 0x0000000629800000|100%| O| |TAMS 0x0000000629400000, 0x0000000629400000| Untracked +| 162|0x0000000629800000, 0x0000000629c00000, 0x0000000629c00000|100%| O| |TAMS 0x0000000629800000, 0x0000000629800000| Untracked +| 163|0x0000000629c00000, 0x000000062a000000, 0x000000062a000000|100%| O| |TAMS 0x0000000629c00000, 0x0000000629c00000| Untracked +| 164|0x000000062a000000, 0x000000062a400000, 0x000000062a400000|100%| O| |TAMS 0x000000062a000000, 0x000000062a000000| Untracked +| 165|0x000000062a400000, 0x000000062a800000, 0x000000062a800000|100%| O| |TAMS 0x000000062a400000, 0x000000062a400000| Untracked +| 166|0x000000062a800000, 0x000000062ac00000, 0x000000062ac00000|100%| O| |TAMS 0x000000062a800000, 0x000000062a800000| Untracked +| 167|0x000000062ac00000, 0x000000062b000000, 0x000000062b000000|100%| O| |TAMS 0x000000062ac00000, 0x000000062ac00000| Untracked +| 168|0x000000062b000000, 0x000000062b400000, 0x000000062b400000|100%| O| |TAMS 0x000000062b000000, 0x000000062b000000| Untracked +| 169|0x000000062b400000, 0x000000062b800000, 0x000000062b800000|100%| O| |TAMS 0x000000062b400000, 0x000000062b400000| Untracked +| 170|0x000000062b800000, 0x000000062bc00000, 0x000000062bc00000|100%| O| |TAMS 0x000000062b800000, 0x000000062b800000| Untracked +| 171|0x000000062bc00000, 0x000000062c000000, 0x000000062c000000|100%| O| |TAMS 0x000000062bc00000, 0x000000062bc00000| Untracked +| 172|0x000000062c000000, 0x000000062c400000, 0x000000062c400000|100%| O| |TAMS 0x000000062c000000, 0x000000062c000000| Untracked +| 173|0x000000062c400000, 0x000000062c800000, 0x000000062c800000|100%| O| |TAMS 0x000000062c400000, 0x000000062c400000| Untracked +| 174|0x000000062c800000, 0x000000062cc00000, 0x000000062cc00000|100%| O| |TAMS 0x000000062c800000, 0x000000062c800000| Untracked +| 175|0x000000062cc00000, 0x000000062d000000, 0x000000062d000000|100%| O| |TAMS 0x000000062cc00000, 0x000000062cc00000| Untracked +| 176|0x000000062d000000, 0x000000062d400000, 0x000000062d400000|100%| O| |TAMS 0x000000062d000000, 0x000000062d000000| Untracked +| 177|0x000000062d400000, 0x000000062d800000, 0x000000062d800000|100%| O| |TAMS 0x000000062d400000, 0x000000062d400000| Untracked +| 178|0x000000062d800000, 0x000000062dc00000, 0x000000062dc00000|100%| O| |TAMS 0x000000062d800000, 0x000000062d800000| Untracked +| 179|0x000000062dc00000, 0x000000062dc00000, 0x000000062e000000| 0%| F| |TAMS 0x000000062dc00000, 0x000000062dc00000| Untracked +| 180|0x000000062e000000, 0x000000062e000000, 0x000000062e400000| 0%| F| |TAMS 0x000000062e000000, 0x000000062e000000| Untracked +| 181|0x000000062e400000, 0x000000062e400000, 0x000000062e800000| 0%| F| |TAMS 0x000000062e400000, 0x000000062e400000| Untracked +| 182|0x000000062e800000, 0x000000062e800000, 0x000000062ec00000| 0%| F| |TAMS 0x000000062e800000, 0x000000062e800000| Untracked +| 183|0x000000062ec00000, 0x000000062ec00000, 0x000000062f000000| 0%| F| |TAMS 0x000000062ec00000, 0x000000062ec00000| Untracked +| 184|0x000000062f000000, 0x000000062f000000, 0x000000062f400000| 0%| F| |TAMS 0x000000062f000000, 0x000000062f000000| Untracked +| 185|0x000000062f400000, 0x000000062f400000, 0x000000062f800000| 0%| F| |TAMS 0x000000062f400000, 0x000000062f400000| Untracked +| 186|0x000000062f800000, 0x000000062f800000, 0x000000062fc00000| 0%| F| |TAMS 0x000000062f800000, 0x000000062f800000| Untracked +| 187|0x000000062fc00000, 0x000000062fc00000, 0x0000000630000000| 0%| F| |TAMS 0x000000062fc00000, 0x000000062fc00000| Untracked +| 188|0x0000000630000000, 0x0000000630000000, 0x0000000630400000| 0%| F| |TAMS 0x0000000630000000, 0x0000000630000000| Untracked +| 189|0x0000000630400000, 0x0000000630400000, 0x0000000630800000| 0%| F| |TAMS 0x0000000630400000, 0x0000000630400000| Untracked +| 190|0x0000000630800000, 0x0000000630800000, 0x0000000630c00000| 0%| F| |TAMS 0x0000000630800000, 0x0000000630800000| Untracked +| 191|0x0000000630c00000, 0x0000000630c00000, 0x0000000631000000| 0%| F| |TAMS 0x0000000630c00000, 0x0000000630c00000| Untracked +| 192|0x0000000631000000, 0x0000000631000000, 0x0000000631400000| 0%| F| |TAMS 0x0000000631000000, 0x0000000631000000| Untracked +| 193|0x0000000631400000, 0x0000000631400000, 0x0000000631800000| 0%| F| |TAMS 0x0000000631400000, 0x0000000631400000| Untracked +| 194|0x0000000631800000, 0x0000000631800000, 0x0000000631c00000| 0%| F| |TAMS 0x0000000631800000, 0x0000000631800000| Untracked +| 195|0x0000000631c00000, 0x0000000631c00000, 0x0000000632000000| 0%| F| |TAMS 0x0000000631c00000, 0x0000000631c00000| Untracked +| 196|0x0000000632000000, 0x0000000632000000, 0x0000000632400000| 0%| F| |TAMS 0x0000000632000000, 0x0000000632000000| Untracked +| 197|0x0000000632400000, 0x0000000632400000, 0x0000000632800000| 0%| F| |TAMS 0x0000000632400000, 0x0000000632400000| Untracked +| 198|0x0000000632800000, 0x0000000632800000, 0x0000000632c00000| 0%| F| |TAMS 0x0000000632800000, 0x0000000632800000| Untracked +| 199|0x0000000632c00000, 0x0000000632c00000, 0x0000000633000000| 0%| F| |TAMS 0x0000000632c00000, 0x0000000632c00000| Untracked +| 200|0x0000000633000000, 0x0000000633000000, 0x0000000633400000| 0%| F| |TAMS 0x0000000633000000, 0x0000000633000000| Untracked +| 201|0x0000000633400000, 0x0000000633400000, 0x0000000633800000| 0%| F| |TAMS 0x0000000633400000, 0x0000000633400000| Untracked +| 202|0x0000000633800000, 0x0000000633800000, 0x0000000633c00000| 0%| F| |TAMS 0x0000000633800000, 0x0000000633800000| Untracked +| 203|0x0000000633c00000, 0x0000000633c00000, 0x0000000634000000| 0%| F| |TAMS 0x0000000633c00000, 0x0000000633c00000| Untracked +| 204|0x0000000634000000, 0x0000000634000000, 0x0000000634400000| 0%| F| |TAMS 0x0000000634000000, 0x0000000634000000| Untracked +| 205|0x0000000634400000, 0x0000000634400000, 0x0000000634800000| 0%| F| |TAMS 0x0000000634400000, 0x0000000634400000| Untracked +| 206|0x0000000634800000, 0x0000000634800000, 0x0000000634c00000| 0%| F| |TAMS 0x0000000634800000, 0x0000000634800000| Untracked +| 207|0x0000000634c00000, 0x0000000634c00000, 0x0000000635000000| 0%| F| |TAMS 0x0000000634c00000, 0x0000000634c00000| Untracked +| 208|0x0000000635000000, 0x0000000635000000, 0x0000000635400000| 0%| F| |TAMS 0x0000000635000000, 0x0000000635000000| Untracked +| 209|0x0000000635400000, 0x0000000635400000, 0x0000000635800000| 0%| F| |TAMS 0x0000000635400000, 0x0000000635400000| Untracked +| 210|0x0000000635800000, 0x0000000635800000, 0x0000000635c00000| 0%| F| |TAMS 0x0000000635800000, 0x0000000635800000| Untracked +| 211|0x0000000635c00000, 0x0000000635c00000, 0x0000000636000000| 0%| F| |TAMS 0x0000000635c00000, 0x0000000635c00000| Untracked +| 212|0x0000000636000000, 0x0000000636000000, 0x0000000636400000| 0%| F| |TAMS 0x0000000636000000, 0x0000000636000000| Untracked +| 213|0x0000000636400000, 0x0000000636400000, 0x0000000636800000| 0%| F| |TAMS 0x0000000636400000, 0x0000000636400000| Untracked +| 214|0x0000000636800000, 0x0000000636800000, 0x0000000636c00000| 0%| F| |TAMS 0x0000000636800000, 0x0000000636800000| Untracked +| 215|0x0000000636c00000, 0x0000000636c00000, 0x0000000637000000| 0%| F| |TAMS 0x0000000636c00000, 0x0000000636c00000| Untracked +| 216|0x0000000637000000, 0x0000000637000000, 0x0000000637400000| 0%| F| |TAMS 0x0000000637000000, 0x0000000637000000| Untracked +| 217|0x0000000637400000, 0x0000000637400000, 0x0000000637800000| 0%| F| |TAMS 0x0000000637400000, 0x0000000637400000| Untracked +| 218|0x0000000637800000, 0x0000000637800000, 0x0000000637c00000| 0%| F| |TAMS 0x0000000637800000, 0x0000000637800000| Untracked +| 219|0x0000000637c00000, 0x0000000637c00000, 0x0000000638000000| 0%| F| |TAMS 0x0000000637c00000, 0x0000000637c00000| Untracked +| 220|0x0000000638000000, 0x0000000638000000, 0x0000000638400000| 0%| F| |TAMS 0x0000000638000000, 0x0000000638000000| Untracked +| 221|0x0000000638400000, 0x0000000638400000, 0x0000000638800000| 0%| F| |TAMS 0x0000000638400000, 0x0000000638400000| Untracked +| 222|0x0000000638800000, 0x0000000638800000, 0x0000000638c00000| 0%| F| |TAMS 0x0000000638800000, 0x0000000638800000| Untracked +| 223|0x0000000638c00000, 0x0000000638c00000, 0x0000000639000000| 0%| F| |TAMS 0x0000000638c00000, 0x0000000638c00000| Untracked +| 224|0x0000000639000000, 0x0000000639000000, 0x0000000639400000| 0%| F| |TAMS 0x0000000639000000, 0x0000000639000000| Untracked +| 225|0x0000000639400000, 0x0000000639400000, 0x0000000639800000| 0%| F| |TAMS 0x0000000639400000, 0x0000000639400000| Untracked +| 226|0x0000000639800000, 0x0000000639800000, 0x0000000639c00000| 0%| F| |TAMS 0x0000000639800000, 0x0000000639800000| Untracked +| 227|0x0000000639c00000, 0x0000000639c00000, 0x000000063a000000| 0%| F| |TAMS 0x0000000639c00000, 0x0000000639c00000| Untracked +| 228|0x000000063a000000, 0x000000063a000000, 0x000000063a400000| 0%| F| |TAMS 0x000000063a000000, 0x000000063a000000| Untracked +| 229|0x000000063a400000, 0x000000063a400000, 0x000000063a800000| 0%| F| |TAMS 0x000000063a400000, 0x000000063a400000| Untracked +| 230|0x000000063a800000, 0x000000063a800000, 0x000000063ac00000| 0%| F| |TAMS 0x000000063a800000, 0x000000063a800000| Untracked +| 231|0x000000063ac00000, 0x000000063ac00000, 0x000000063b000000| 0%| F| |TAMS 0x000000063ac00000, 0x000000063ac00000| Untracked +| 232|0x000000063b000000, 0x000000063b000000, 0x000000063b400000| 0%| F| |TAMS 0x000000063b000000, 0x000000063b000000| Untracked +| 233|0x000000063b400000, 0x000000063b400000, 0x000000063b800000| 0%| F| |TAMS 0x000000063b400000, 0x000000063b400000| Untracked +| 234|0x000000063b800000, 0x000000063b800000, 0x000000063bc00000| 0%| F| |TAMS 0x000000063b800000, 0x000000063b800000| Untracked +| 235|0x000000063bc00000, 0x000000063bc00000, 0x000000063c000000| 0%| F| |TAMS 0x000000063bc00000, 0x000000063bc00000| Untracked +| 236|0x000000063c000000, 0x000000063c000000, 0x000000063c400000| 0%| F| |TAMS 0x000000063c000000, 0x000000063c000000| Untracked +| 237|0x000000063c400000, 0x000000063c400000, 0x000000063c800000| 0%| F| |TAMS 0x000000063c400000, 0x000000063c400000| Untracked +| 238|0x000000063c800000, 0x000000063c800000, 0x000000063cc00000| 0%| F| |TAMS 0x000000063c800000, 0x000000063c800000| Untracked +| 239|0x000000063cc00000, 0x000000063cc00000, 0x000000063d000000| 0%| F| |TAMS 0x000000063cc00000, 0x000000063cc00000| Untracked +| 240|0x000000063d000000, 0x000000063d000000, 0x000000063d400000| 0%| F| |TAMS 0x000000063d000000, 0x000000063d000000| Untracked +| 241|0x000000063d400000, 0x000000063d400000, 0x000000063d800000| 0%| F| |TAMS 0x000000063d400000, 0x000000063d400000| Untracked +| 242|0x000000063d800000, 0x000000063d800000, 0x000000063dc00000| 0%| F| |TAMS 0x000000063d800000, 0x000000063d800000| Untracked +| 243|0x000000063dc00000, 0x000000063dc00000, 0x000000063e000000| 0%| F| |TAMS 0x000000063dc00000, 0x000000063dc00000| Untracked +| 244|0x000000063e000000, 0x000000063e000000, 0x000000063e400000| 0%| F| |TAMS 0x000000063e000000, 0x000000063e000000| Untracked +| 245|0x000000063e400000, 0x000000063e400000, 0x000000063e800000| 0%| F| |TAMS 0x000000063e400000, 0x000000063e400000| Untracked +| 246|0x000000063e800000, 0x000000063e800000, 0x000000063ec00000| 0%| F| |TAMS 0x000000063e800000, 0x000000063e800000| Untracked +| 247|0x000000063ec00000, 0x000000063ec00000, 0x000000063f000000| 0%| F| |TAMS 0x000000063ec00000, 0x000000063ec00000| Untracked +| 248|0x000000063f000000, 0x000000063f000000, 0x000000063f400000| 0%| F| |TAMS 0x000000063f000000, 0x000000063f000000| Untracked +| 249|0x000000063f400000, 0x000000063f400000, 0x000000063f800000| 0%| F| |TAMS 0x000000063f400000, 0x000000063f400000| Untracked +| 250|0x000000063f800000, 0x000000063f800000, 0x000000063fc00000| 0%| F| |TAMS 0x000000063f800000, 0x000000063f800000| Untracked +| 251|0x000000063fc00000, 0x000000063fc00000, 0x0000000640000000| 0%| F| |TAMS 0x000000063fc00000, 0x000000063fc00000| Untracked +| 252|0x0000000640000000, 0x0000000640000000, 0x0000000640400000| 0%| F| |TAMS 0x0000000640000000, 0x0000000640000000| Untracked +| 253|0x0000000640400000, 0x0000000640400000, 0x0000000640800000| 0%| F| |TAMS 0x0000000640400000, 0x0000000640400000| Untracked +| 254|0x0000000640800000, 0x0000000640800000, 0x0000000640c00000| 0%| F| |TAMS 0x0000000640800000, 0x0000000640800000| Untracked +| 255|0x0000000640c00000, 0x0000000640c00000, 0x0000000641000000| 0%| F| |TAMS 0x0000000640c00000, 0x0000000640c00000| Untracked +| 256|0x0000000641000000, 0x0000000641000000, 0x0000000641400000| 0%| F| |TAMS 0x0000000641000000, 0x0000000641000000| Untracked +| 257|0x0000000641400000, 0x0000000641400000, 0x0000000641800000| 0%| F| |TAMS 0x0000000641400000, 0x0000000641400000| Untracked +| 258|0x0000000641800000, 0x0000000641800000, 0x0000000641c00000| 0%| F| |TAMS 0x0000000641800000, 0x0000000641800000| Untracked +| 259|0x0000000641c00000, 0x0000000641c00000, 0x0000000642000000| 0%| F| |TAMS 0x0000000641c00000, 0x0000000641c00000| Untracked +| 260|0x0000000642000000, 0x0000000642000000, 0x0000000642400000| 0%| F| |TAMS 0x0000000642000000, 0x0000000642000000| Untracked +| 261|0x0000000642400000, 0x0000000642400000, 0x0000000642800000| 0%| F| |TAMS 0x0000000642400000, 0x0000000642400000| Untracked +| 262|0x0000000642800000, 0x0000000642800000, 0x0000000642c00000| 0%| F| |TAMS 0x0000000642800000, 0x0000000642800000| Untracked +| 263|0x0000000642c00000, 0x0000000642c00000, 0x0000000643000000| 0%| F| |TAMS 0x0000000642c00000, 0x0000000642c00000| Untracked +| 264|0x0000000643000000, 0x0000000643000000, 0x0000000643400000| 0%| F| |TAMS 0x0000000643000000, 0x0000000643000000| Untracked +| 265|0x0000000643400000, 0x0000000643400000, 0x0000000643800000| 0%| F| |TAMS 0x0000000643400000, 0x0000000643400000| Untracked +| 266|0x0000000643800000, 0x0000000643800000, 0x0000000643c00000| 0%| F| |TAMS 0x0000000643800000, 0x0000000643800000| Untracked +| 267|0x0000000643c00000, 0x0000000643c00000, 0x0000000644000000| 0%| F| |TAMS 0x0000000643c00000, 0x0000000643c00000| Untracked +| 268|0x0000000644000000, 0x0000000644000000, 0x0000000644400000| 0%| F| |TAMS 0x0000000644000000, 0x0000000644000000| Untracked +| 269|0x0000000644400000, 0x0000000644400000, 0x0000000644800000| 0%| F| |TAMS 0x0000000644400000, 0x0000000644400000| Untracked +| 270|0x0000000644800000, 0x0000000644800000, 0x0000000644c00000| 0%| F| |TAMS 0x0000000644800000, 0x0000000644800000| Untracked +| 271|0x0000000644c00000, 0x0000000644c00000, 0x0000000645000000| 0%| F| |TAMS 0x0000000644c00000, 0x0000000644c00000| Untracked +| 272|0x0000000645000000, 0x0000000645000000, 0x0000000645400000| 0%| F| |TAMS 0x0000000645000000, 0x0000000645000000| Untracked +| 273|0x0000000645400000, 0x0000000645400000, 0x0000000645800000| 0%| F| |TAMS 0x0000000645400000, 0x0000000645400000| Untracked +| 274|0x0000000645800000, 0x0000000645800000, 0x0000000645c00000| 0%| F| |TAMS 0x0000000645800000, 0x0000000645800000| Untracked +| 275|0x0000000645c00000, 0x0000000645c00000, 0x0000000646000000| 0%| F| |TAMS 0x0000000645c00000, 0x0000000645c00000| Untracked +| 276|0x0000000646000000, 0x0000000646000000, 0x0000000646400000| 0%| F| |TAMS 0x0000000646000000, 0x0000000646000000| Untracked +| 277|0x0000000646400000, 0x0000000646400000, 0x0000000646800000| 0%| F| |TAMS 0x0000000646400000, 0x0000000646400000| Untracked +| 278|0x0000000646800000, 0x0000000646800000, 0x0000000646c00000| 0%| F| |TAMS 0x0000000646800000, 0x0000000646800000| Untracked +| 279|0x0000000646c00000, 0x0000000646c00000, 0x0000000647000000| 0%| F| |TAMS 0x0000000646c00000, 0x0000000646c00000| Untracked +| 280|0x0000000647000000, 0x0000000647000000, 0x0000000647400000| 0%| F| |TAMS 0x0000000647000000, 0x0000000647000000| Untracked +| 281|0x0000000647400000, 0x0000000647400000, 0x0000000647800000| 0%| F| |TAMS 0x0000000647400000, 0x0000000647400000| Untracked +| 282|0x0000000647800000, 0x0000000647800000, 0x0000000647c00000| 0%| F| |TAMS 0x0000000647800000, 0x0000000647800000| Untracked +| 283|0x0000000647c00000, 0x0000000647c00000, 0x0000000648000000| 0%| F| |TAMS 0x0000000647c00000, 0x0000000647c00000| Untracked +| 284|0x0000000648000000, 0x0000000648000000, 0x0000000648400000| 0%| F| |TAMS 0x0000000648000000, 0x0000000648000000| Untracked +| 285|0x0000000648400000, 0x0000000648400000, 0x0000000648800000| 0%| F| |TAMS 0x0000000648400000, 0x0000000648400000| Untracked +| 286|0x0000000648800000, 0x0000000648800000, 0x0000000648c00000| 0%| F| |TAMS 0x0000000648800000, 0x0000000648800000| Untracked +| 287|0x0000000648c00000, 0x0000000648c00000, 0x0000000649000000| 0%| F| |TAMS 0x0000000648c00000, 0x0000000648c00000| Untracked +| 288|0x0000000649000000, 0x0000000649000000, 0x0000000649400000| 0%| F| |TAMS 0x0000000649000000, 0x0000000649000000| Untracked +| 289|0x0000000649400000, 0x0000000649400000, 0x0000000649800000| 0%| F| |TAMS 0x0000000649400000, 0x0000000649400000| Untracked +| 290|0x0000000649800000, 0x0000000649800000, 0x0000000649c00000| 0%| F| |TAMS 0x0000000649800000, 0x0000000649800000| Untracked +| 291|0x0000000649c00000, 0x0000000649c00000, 0x000000064a000000| 0%| F| |TAMS 0x0000000649c00000, 0x0000000649c00000| Untracked +| 292|0x000000064a000000, 0x000000064a000000, 0x000000064a400000| 0%| F| |TAMS 0x000000064a000000, 0x000000064a000000| Untracked +| 293|0x000000064a400000, 0x000000064a400000, 0x000000064a800000| 0%| F| |TAMS 0x000000064a400000, 0x000000064a400000| Untracked +| 294|0x000000064a800000, 0x000000064a800000, 0x000000064ac00000| 0%| F| |TAMS 0x000000064a800000, 0x000000064a800000| Untracked +| 295|0x000000064ac00000, 0x000000064ac00000, 0x000000064b000000| 0%| F| |TAMS 0x000000064ac00000, 0x000000064ac00000| Untracked +| 296|0x000000064b000000, 0x000000064b000000, 0x000000064b400000| 0%| F| |TAMS 0x000000064b000000, 0x000000064b000000| Untracked +| 297|0x000000064b400000, 0x000000064b400000, 0x000000064b800000| 0%| F| |TAMS 0x000000064b400000, 0x000000064b400000| Untracked +| 298|0x000000064b800000, 0x000000064b800000, 0x000000064bc00000| 0%| F| |TAMS 0x000000064b800000, 0x000000064b800000| Untracked +| 299|0x000000064bc00000, 0x000000064bc00000, 0x000000064c000000| 0%| F| |TAMS 0x000000064bc00000, 0x000000064bc00000| Untracked +| 300|0x000000064c000000, 0x000000064c000000, 0x000000064c400000| 0%| F| |TAMS 0x000000064c000000, 0x000000064c000000| Untracked +| 301|0x000000064c400000, 0x000000064c400000, 0x000000064c800000| 0%| F| |TAMS 0x000000064c400000, 0x000000064c400000| Untracked +| 302|0x000000064c800000, 0x000000064c800000, 0x000000064cc00000| 0%| F| |TAMS 0x000000064c800000, 0x000000064c800000| Untracked +| 303|0x000000064cc00000, 0x000000064cc00000, 0x000000064d000000| 0%| F| |TAMS 0x000000064cc00000, 0x000000064cc00000| Untracked +| 304|0x000000064d000000, 0x000000064d000000, 0x000000064d400000| 0%| F| |TAMS 0x000000064d000000, 0x000000064d000000| Untracked +| 305|0x000000064d400000, 0x000000064d400000, 0x000000064d800000| 0%| F| |TAMS 0x000000064d400000, 0x000000064d400000| Untracked +| 306|0x000000064d800000, 0x000000064d800000, 0x000000064dc00000| 0%| F| |TAMS 0x000000064d800000, 0x000000064d800000| Untracked +| 307|0x000000064dc00000, 0x000000064dc00000, 0x000000064e000000| 0%| F| |TAMS 0x000000064dc00000, 0x000000064dc00000| Untracked +| 308|0x000000064e000000, 0x000000064e000000, 0x000000064e400000| 0%| F| |TAMS 0x000000064e000000, 0x000000064e000000| Untracked +| 309|0x000000064e400000, 0x000000064e400000, 0x000000064e800000| 0%| F| |TAMS 0x000000064e400000, 0x000000064e400000| Untracked +| 310|0x000000064e800000, 0x000000064e800000, 0x000000064ec00000| 0%| F| |TAMS 0x000000064e800000, 0x000000064e800000| Untracked +| 311|0x000000064ec00000, 0x000000064ec00000, 0x000000064f000000| 0%| F| |TAMS 0x000000064ec00000, 0x000000064ec00000| Untracked +| 312|0x000000064f000000, 0x000000064f000000, 0x000000064f400000| 0%| F| |TAMS 0x000000064f000000, 0x000000064f000000| Untracked +| 313|0x000000064f400000, 0x000000064f400000, 0x000000064f800000| 0%| F| |TAMS 0x000000064f400000, 0x000000064f400000| Untracked +| 314|0x000000064f800000, 0x000000064f800000, 0x000000064fc00000| 0%| F| |TAMS 0x000000064f800000, 0x000000064f800000| Untracked +| 315|0x000000064fc00000, 0x000000064fc00000, 0x0000000650000000| 0%| F| |TAMS 0x000000064fc00000, 0x000000064fc00000| Untracked +| 316|0x0000000650000000, 0x0000000650000000, 0x0000000650400000| 0%| F| |TAMS 0x0000000650000000, 0x0000000650000000| Untracked +| 317|0x0000000650400000, 0x0000000650400000, 0x0000000650800000| 0%| F| |TAMS 0x0000000650400000, 0x0000000650400000| Untracked +| 318|0x0000000650800000, 0x0000000650800000, 0x0000000650c00000| 0%| F| |TAMS 0x0000000650800000, 0x0000000650800000| Untracked +| 319|0x0000000650c00000, 0x0000000650c00000, 0x0000000651000000| 0%| F| |TAMS 0x0000000650c00000, 0x0000000650c00000| Untracked +| 320|0x0000000651000000, 0x0000000651000000, 0x0000000651400000| 0%| F| |TAMS 0x0000000651000000, 0x0000000651000000| Untracked +| 321|0x0000000651400000, 0x0000000651400000, 0x0000000651800000| 0%| F| |TAMS 0x0000000651400000, 0x0000000651400000| Untracked +| 322|0x0000000651800000, 0x0000000651800000, 0x0000000651c00000| 0%| F| |TAMS 0x0000000651800000, 0x0000000651800000| Untracked +| 323|0x0000000651c00000, 0x0000000651f2dc78, 0x0000000652000000| 79%| S|CS|TAMS 0x0000000651c00000, 0x0000000651c00000| Complete +| 324|0x0000000652000000, 0x0000000652400000, 0x0000000652400000|100%| S|CS|TAMS 0x0000000652000000, 0x0000000652000000| Complete +| 325|0x0000000652400000, 0x0000000652400000, 0x0000000652800000| 0%| F| |TAMS 0x0000000652400000, 0x0000000652400000| Untracked +| 326|0x0000000652800000, 0x0000000652800000, 0x0000000652c00000| 0%| F| |TAMS 0x0000000652800000, 0x0000000652800000| Untracked +| 327|0x0000000652c00000, 0x0000000652c00000, 0x0000000653000000| 0%| F| |TAMS 0x0000000652c00000, 0x0000000652c00000| Untracked +| 328|0x0000000653000000, 0x0000000653000000, 0x0000000653400000| 0%| F| |TAMS 0x0000000653000000, 0x0000000653000000| Untracked +| 329|0x0000000653400000, 0x0000000653400000, 0x0000000653800000| 0%| F| |TAMS 0x0000000653400000, 0x0000000653400000| Untracked +| 330|0x0000000653800000, 0x0000000653800000, 0x0000000653c00000| 0%| F| |TAMS 0x0000000653800000, 0x0000000653800000| Untracked +| 331|0x0000000653c00000, 0x0000000653c00000, 0x0000000654000000| 0%| F| |TAMS 0x0000000653c00000, 0x0000000653c00000| Untracked +| 332|0x0000000654000000, 0x0000000654000000, 0x0000000654400000| 0%| F| |TAMS 0x0000000654000000, 0x0000000654000000| Untracked +| 333|0x0000000654400000, 0x0000000654400000, 0x0000000654800000| 0%| F| |TAMS 0x0000000654400000, 0x0000000654400000| Untracked +| 334|0x0000000654800000, 0x0000000654800000, 0x0000000654c00000| 0%| F| |TAMS 0x0000000654800000, 0x0000000654800000| Untracked +| 335|0x0000000654c00000, 0x0000000654c00000, 0x0000000655000000| 0%| F| |TAMS 0x0000000654c00000, 0x0000000654c00000| Untracked +| 336|0x0000000655000000, 0x0000000655000000, 0x0000000655400000| 0%| F| |TAMS 0x0000000655000000, 0x0000000655000000| Untracked +| 337|0x0000000655400000, 0x0000000655400000, 0x0000000655800000| 0%| F| |TAMS 0x0000000655400000, 0x0000000655400000| Untracked +| 338|0x0000000655800000, 0x0000000655800000, 0x0000000655c00000| 0%| F| |TAMS 0x0000000655800000, 0x0000000655800000| Untracked +| 339|0x0000000655c00000, 0x0000000655c00000, 0x0000000656000000| 0%| F| |TAMS 0x0000000655c00000, 0x0000000655c00000| Untracked +| 340|0x0000000656000000, 0x0000000656000000, 0x0000000656400000| 0%| F| |TAMS 0x0000000656000000, 0x0000000656000000| Untracked +| 341|0x0000000656400000, 0x0000000656400000, 0x0000000656800000| 0%| F| |TAMS 0x0000000656400000, 0x0000000656400000| Untracked + +Card table byte_map: [0x000002576ca50000,0x000002576da50000] _byte_map_base: 0x0000025769a48000 + +Marking Bits (Prev, Next): (CMBitMap*) 0x000002575446c810, (CMBitMap*) 0x000002575446c850 + Prev Bits: [0x000002576ea50000, 0x0000025776a10000) + Next Bits: [0x0000025776a10000, 0x000002577e9d0000) + +Polling page: 0x0000025752b40000 + +Metaspace: + +Usage: + Non-class: 42.90 MB used. + Class: 5.31 MB used. + Both: 48.21 MB used. + +Virtual space: + Non-class space: 64.00 MB reserved, 48.31 MB ( 75%) committed, 1 nodes. + Class space: 1.00 GB reserved, 7.00 MB ( <1%) committed, 1 nodes. + Both: 1.06 GB reserved, 55.31 MB ( 5%) committed. + +Chunk freelists: + Non-Class: 20.77 MB + Class: 10.33 MB + Both: 31.11 MB + +MaxMetaspaceSize: unlimited +CompressedClassSpaceSize: 1.00 GB +Initial GC threshold: 21.00 MB +Current GC threshold: 92.19 MB +CDS: on +MetaspaceReclaimPolicy: balanced + - commit_granule_bytes: 65536. + - commit_granule_words: 8192. + - virtual_space_node_default_size: 8388608. + - enlarge_chunks_in_place: 1. + - new_chunks_are_fully_committed: 0. + - uncommit_free_chunks: 1. + - use_allocation_guard: 0. + - handle_deallocations: 1. + + +Internal statistics: + +num_allocs_failed_limit: 17. +num_arena_births: 758. +num_arena_deaths: 140. +num_vsnodes_births: 2. +num_vsnodes_deaths: 0. +num_space_committed: 1232. +num_space_uncommitted: 347. +num_chunks_returned_to_freelist: 2252. +num_chunks_taken_from_freelist: 5191. +num_chunk_merges: 689. +num_chunk_splits: 2844. +num_chunks_enlarged: 1361. +num_inconsistent_stats: 0. + +CodeHeap 'non-profiled nmethods': size=120000Kb used=13845Kb max_used=14768Kb free=106154Kb + bounds [0x0000025763ac0000, 0x0000025764930000, 0x000002576aff0000] +CodeHeap 'profiled nmethods': size=120000Kb used=25344Kb max_used=29850Kb free=94655Kb + bounds [0x000002575bff0000, 0x000002575dd20000, 0x0000025763520000] +CodeHeap 'non-nmethods': size=5760Kb used=1250Kb max_used=1534Kb free=4509Kb + bounds [0x0000025763520000, 0x0000025763790000, 0x0000025763ac0000] + total_blobs=13033 nmethods=12471 adapters=473 + compilation: enabled + stopped_count=0, restarted_count=0 + full_count=0 + +Compilation events (20 events): +Event: 21.747 Thread 0x000002577ec34090 20241 3 com.sun.tools.javac.comp.TypeEnter$HierarchyPhase::clearTypeParams (38 bytes) +Event: 21.747 Thread 0x000002577ec34090 nmethod 20241 0x000002575ccc7b90 code [0x000002575ccc7d60, 0x000002575ccc8108] +Event: 21.747 Thread 0x000002577ec34090 20242 3 com.sun.tools.javac.comp.Check$CycleChecker::visitIdent (13 bytes) +Event: 21.747 Thread 0x000002577ec34090 nmethod 20242 0x000002575ce5fb10 code [0x000002575ce5fcc0, 0x000002575ce5fee8] +Event: 21.747 Thread 0x000002577ec34090 20243 2 lombok.javac.JavacASTAdapter::endVisitCompilationUnit (1 bytes) +Event: 21.747 Thread 0x000002577ec34090 nmethod 20243 0x000002575d125290 code [0x000002575d125420, 0x000002575d125518] +Event: 21.749 Thread 0x000002577ec34090 20244 2 lombok.javac.handlers.HandleVal::eq (58 bytes) +Event: 21.749 Thread 0x000002577ec34090 nmethod 20244 0x000002575c759710 code [0x000002575c759940, 0x000002575c759d48] +Event: 21.750 Thread 0x000002577ec34090 20245 2 lombok.javac.JavacASTAdapter::visitAnnotationOnMethod (1 bytes) +Event: 21.750 Thread 0x000002577ec34090 nmethod 20245 0x000002575d379f90 code [0x000002575d37a120, 0x000002575d37a218] +Event: 21.751 Thread 0x000002577ec34090 20246 ! 2 lombok.javac.handlers.HandleVal::endVisitLocal (993 bytes) +Event: 21.755 Thread 0x000002577ec34090 nmethod 20246 0x000002575d413b90 code [0x000002575d4143e0, 0x000002575d417218] +Event: 21.755 Thread 0x000002577ec34090 20247 2 lombok.permit.Permit::setAccessible (27 bytes) +Event: 21.755 Thread 0x000002577ec34090 nmethod 20247 0x000002575d486d10 code [0x000002575d486ea0, 0x000002575d486f98] +Event: 21.759 Thread 0x000002577ec34090 20248 ! 2 lombok.javac.JavacAST::getBodyMethod (64 bytes) +Event: 21.759 Thread 0x000002577ec34090 nmethod 20248 0x000002575c3f6d90 code [0x000002575c3f6f80, 0x000002575c3f7368] +Event: 21.760 Thread 0x000002577ec34090 20249 2 com.sun.tools.javac.comp.TypeEnter::ensureImportsChecked (62 bytes) +Event: 21.761 Thread 0x000002577ec34090 nmethod 20249 0x000002575c7ad110 code [0x000002575c7ad320, 0x000002575c7ad8c8] +Event: 21.772 Thread 0x000002577ec34090 20255 2 com.sun.tools.javac.comp.Check::checkRefType (26 bytes) +Event: 21.772 Thread 0x000002577ec34090 nmethod 20255 0x000002575c9d3c10 code [0x000002575c9d3de0, 0x000002575c9d3fc8] + +GC Heap History (20 events): +Event: 14.570 GC heap after +{Heap after GC invocations=35 (full 0): + garbage-first heap total 1167360K, used 424005K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 8 young (32768K), 8 survivors (32768K) + Metaspace used 61566K, committed 62592K, reserved 1114112K + class space used 6957K, committed 7424K, reserved 1048576K +} +Event: 16.908 GC heap before +{Heap before GC invocations=35 (full 0): + garbage-first heap total 1167360K, used 862277K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 115 young (471040K), 8 survivors (32768K) + Metaspace used 62236K, committed 63232K, reserved 1114112K + class space used 7020K, committed 7488K, reserved 1048576K +} +Event: 16.929 GC heap after +{Heap after GC invocations=36 (full 0): + garbage-first heap total 1167360K, used 495229K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 15 young (61440K), 15 survivors (61440K) + Metaspace used 62236K, committed 63232K, reserved 1114112K + class space used 7020K, committed 7488K, reserved 1048576K +} +Event: 17.969 GC heap before +{Heap before GC invocations=36 (full 0): + garbage-first heap total 1167360K, used 863869K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 106 young (434176K), 15 survivors (61440K) + Metaspace used 63393K, committed 64512K, reserved 1114112K + class space used 7148K, committed 7616K, reserved 1048576K +} +Event: 18.001 GC heap after +{Heap after GC invocations=37 (full 0): + garbage-first heap total 1167360K, used 588618K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 14 young (57344K), 14 survivors (57344K) + Metaspace used 63393K, committed 64512K, reserved 1114112K + class space used 7148K, committed 7616K, reserved 1048576K +} +Event: 18.755 GC heap before +{Heap before GC invocations=37 (full 0): + garbage-first heap total 1167360K, used 879434K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 86 young (352256K), 14 survivors (57344K) + Metaspace used 68268K, committed 69376K, reserved 1114112K + class space used 7712K, committed 8192K, reserved 1048576K +} +Event: 18.777 GC heap after +{Heap after GC invocations=38 (full 0): + garbage-first heap total 1167360K, used 621836K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 8 young (32768K), 8 survivors (32768K) + Metaspace used 68268K, committed 69376K, reserved 1114112K + class space used 7712K, committed 8192K, reserved 1048576K +} +Event: 19.223 GC heap before +{Heap before GC invocations=38 (full 0): + garbage-first heap total 1167360K, used 904460K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 78 young (319488K), 8 survivors (32768K) + Metaspace used 69902K, committed 71104K, reserved 1114112K + class space used 7909K, committed 8448K, reserved 1048576K +} +Event: 19.236 GC heap after +{Heap after GC invocations=39 (full 0): + garbage-first heap total 1167360K, used 636231K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 3 young (12288K), 3 survivors (12288K) + Metaspace used 69902K, committed 71104K, reserved 1114112K + class space used 7909K, committed 8448K, reserved 1048576K +} +Event: 19.750 GC heap before +{Heap before GC invocations=39 (full 0): + garbage-first heap total 1167360K, used 922951K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 74 young (303104K), 3 survivors (12288K) + Metaspace used 70950K, committed 72064K, reserved 1114112K + class space used 8006K, committed 8512K, reserved 1048576K +} +Event: 19.765 GC heap after +{Heap after GC invocations=40 (full 0): + garbage-first heap total 1400832K, used 652012K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 7 young (28672K), 7 survivors (28672K) + Metaspace used 70950K, committed 72064K, reserved 1114112K + class space used 8006K, committed 8512K, reserved 1048576K +} +Event: 20.441 GC heap before +{Heap before GC invocations=40 (full 0): + garbage-first heap total 1400832K, used 1086188K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 113 young (462848K), 7 survivors (28672K) + Metaspace used 71423K, committed 72576K, reserved 1114112K + class space used 8062K, committed 8576K, reserved 1048576K +} +Event: 20.465 GC heap after +{Heap after GC invocations=41 (full 0): + garbage-first heap total 1400832K, used 692441K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 15 young (61440K), 15 survivors (61440K) + Metaspace used 71423K, committed 72576K, reserved 1114112K + class space used 8062K, committed 8576K, reserved 1048576K +} +Event: 20.964 GC heap before +{Heap before GC invocations=41 (full 0): + garbage-first heap total 1400832K, used 1069273K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 108 young (442368K), 15 survivors (61440K) + Metaspace used 72709K, committed 73856K, reserved 1114112K + class space used 8207K, committed 8768K, reserved 1048576K +} +Event: 20.987 GC heap after +{Heap after GC invocations=42 (full 0): + garbage-first heap total 1400832K, used 720801K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 7 young (28672K), 7 survivors (28672K) + Metaspace used 72709K, committed 73856K, reserved 1114112K + class space used 8207K, committed 8768K, reserved 1048576K +} +Event: 21.637 GC heap before +{Heap before GC invocations=43 (full 0): + garbage-first heap total 1400832K, used 1122209K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 106 young (434176K), 7 survivors (28672K) + Metaspace used 49336K, committed 56640K, reserved 1114112K + class space used 5434K, committed 7168K, reserved 1048576K +} +Event: 21.648 GC heap after +{Heap after GC invocations=44 (full 0): + garbage-first heap total 1400832K, used 723685K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 7 young (28672K), 7 survivors (28672K) + Metaspace used 49336K, committed 56640K, reserved 1114112K + class space used 5434K, committed 7168K, reserved 1048576K +} +Event: 21.701 GC heap before +{Heap before GC invocations=44 (full 0): + garbage-first heap total 1400832K, used 760549K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 17 young (69632K), 7 survivors (28672K) + Metaspace used 49343K, committed 56640K, reserved 1114112K + class space used 5435K, committed 7168K, reserved 1048576K +} +Event: 21.712 GC heap after +{Heap after GC invocations=45 (full 0): + garbage-first heap total 1400832K, used 591919K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 2 young (8192K), 2 survivors (8192K) + Metaspace used 49343K, committed 56640K, reserved 1114112K + class space used 5435K, committed 7168K, reserved 1048576K +} +Event: 21.792 GC heap before +{Heap before GC invocations=45 (full 0): + garbage-first heap total 1400832K, used 653359K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 17 young (69632K), 2 survivors (8192K) + Metaspace used 49364K, committed 56640K, reserved 1114112K + class space used 5435K, committed 7168K, reserved 1048576K +} + +Deoptimization events (20 events): +Event: 21.736 Thread 0x0000025747e837f0 Uncommon trap: trap_request=0xffffffc6 fr.pc=0x0000025763fe00f0 relative=0x0000000000000ff0 +Event: 21.736 Thread 0x0000025747e837f0 Uncommon trap: reason=bimorphic_or_optimized_type_check action=maybe_recompile pc=0x0000025763fe00f0 method=lombok.javac.JavacNode.traverse(Llombok/javac/JavacASTVisitor;)V @ 490 c2 +Event: 21.736 Thread 0x0000025747e837f0 DEOPT PACKING pc=0x0000025763fe00f0 sp=0x000000a0caffd680 +Event: 21.736 Thread 0x0000025747e837f0 DEOPT UNPACKING pc=0x00000257635723a3 sp=0x000000a0caffd600 mode 2 +Event: 21.781 Thread 0x0000025747e83d00 Uncommon trap: trap_request=0xffffffde fr.pc=0x00000257648c60f4 relative=0x00000000000000d4 +Event: 21.781 Thread 0x0000025747e83d00 Uncommon trap: reason=class_check action=maybe_recompile pc=0x00000257648c60f4 method=java.lang.Character.toLowerCase(I)I @ 5 c2 +Event: 21.781 Thread 0x0000025747e83d00 DEOPT PACKING pc=0x00000257648c60f4 sp=0x000000a0cb0fe0e0 +Event: 21.781 Thread 0x0000025747e83d00 DEOPT UNPACKING pc=0x00000257635723a3 sp=0x000000a0cb0fe078 mode 2 +Event: 21.781 Thread 0x0000025747e83d00 Uncommon trap: trap_request=0xffffffde fr.pc=0x00000257648c60f4 relative=0x00000000000000d4 +Event: 21.781 Thread 0x0000025747e83d00 Uncommon trap: reason=class_check action=maybe_recompile pc=0x00000257648c60f4 method=java.lang.Character.toLowerCase(I)I @ 5 c2 +Event: 21.781 Thread 0x0000025747e83d00 DEOPT PACKING pc=0x00000257648c60f4 sp=0x000000a0cb0fe0e0 +Event: 21.781 Thread 0x0000025747e83d00 DEOPT UNPACKING pc=0x00000257635723a3 sp=0x000000a0cb0fe078 mode 2 +Event: 21.781 Thread 0x0000025747e83d00 Uncommon trap: trap_request=0xffffffde fr.pc=0x00000257648c60f4 relative=0x00000000000000d4 +Event: 21.781 Thread 0x0000025747e83d00 Uncommon trap: reason=class_check action=maybe_recompile pc=0x00000257648c60f4 method=java.lang.Character.toLowerCase(I)I @ 5 c2 +Event: 21.781 Thread 0x0000025747e83d00 DEOPT PACKING pc=0x00000257648c60f4 sp=0x000000a0cb0fe0e0 +Event: 21.781 Thread 0x0000025747e83d00 DEOPT UNPACKING pc=0x00000257635723a3 sp=0x000000a0cb0fe078 mode 2 +Event: 21.781 Thread 0x0000025747e83d00 Uncommon trap: trap_request=0xffffffde fr.pc=0x00000257648c60f4 relative=0x00000000000000d4 +Event: 21.781 Thread 0x0000025747e83d00 Uncommon trap: reason=class_check action=maybe_recompile pc=0x00000257648c60f4 method=java.lang.Character.toLowerCase(I)I @ 5 c2 +Event: 21.781 Thread 0x0000025747e83d00 DEOPT PACKING pc=0x00000257648c60f4 sp=0x000000a0cb0fe0e0 +Event: 21.781 Thread 0x0000025747e83d00 DEOPT UNPACKING pc=0x00000257635723a3 sp=0x000000a0cb0fe078 mode 2 + +Classes unloaded (20 events): +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d1808 'org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d15e8 'org/springframework/boot/configurationprocessor/TypeUtils$$Lambda$694+0x00000257034d15e8' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d12c8 'org/springframework/boot/configurationprocessor/TypeUtils$TypeExtractor' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d1098 'org/springframework/boot/configurationprocessor/TypeUtils$$Lambda$688+0x00000257034d1098' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d0e40 'org/springframework/boot/configurationprocessor/TypeUtils' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d0c08 'org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata$$Lambda$687+0x00000257034d0c08' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d09e8 'org/springframework/boot/configurationprocessor/metadata/ItemMetadata' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d07e8 'org/springframework/boot/configurationprocessor/json/JSON' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d05a8 'org/springframework/boot/configurationprocessor/metadata/ItemMetadata$ItemType' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d0270 'org/springframework/boot/configurationprocessor/json/JSONArray' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034d0000 'org/springframework/boot/configurationprocessor/json/JSONTokener' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034ccc08 'org/springframework/boot/configurationprocessor/json/JSONObject$1' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034cc9b0 'org/springframework/boot/configurationprocessor/json/JSONException' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034cc678 'org/springframework/boot/configurationprocessor/json/JSONObject' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034cc438 'org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadata' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034cc228 'org/springframework/boot/configurationprocessor/metadata/JsonMarshaller' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257034cc000 'org/springframework/boot/configurationprocessor/MetadataCollector' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x0000025703364530 'org/springframework/boot/configurationprocessor/MetadataStore' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x00000257033642d0 'org/springframework/boot/configurationprocessor/metadata/InvalidConfigurationMetadataException' +Event: 21.132 Thread 0x000002577ec0ce20 Unloading class 0x0000025703364000 'org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor' + +Classes redefined (0 events): +No events + +Internal exceptions (20 events): +Event: 21.715 Thread 0x0000025747e83d00 Exception (0x00000006566273d0) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.716 Thread 0x0000025747e837f0 Exception (0x000000065666ab88) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.716 Thread 0x0000025747e837f0 Exception (0x000000065666ad40) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.716 Thread 0x0000025747e837f0 Exception (0x000000065666bcb8) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.716 Thread 0x0000025747e837f0 Exception (0x000000065666beb8) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.716 Thread 0x0000025747e837f0 Exception (0x000000065666cf18) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.716 Thread 0x0000025747e837f0 Exception (0x000000065666d0e0) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.720 Thread 0x0000025747e83d00 Exception (0x00000006567f6850) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.720 Thread 0x0000025747e83d00 Exception (0x00000006567f6f40) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.720 Thread 0x0000025747e83d00 Exception (0x00000006567f78d0) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.725 Thread 0x0000025747e83d00 Exception (0x0000000655e1fb00) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.725 Thread 0x0000025747e83d00 Exception (0x0000000655e20220) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.725 Thread 0x0000025747e83d00 Exception (0x0000000655e20cb8) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.725 Thread 0x0000025747e83d00 Exception (0x0000000655e21458) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.766 Thread 0x0000025747e837f0 Exception (0x00000006541cbb00) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.766 Thread 0x0000025747e837f0 Exception (0x00000006541cbcb8) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.766 Thread 0x0000025747e837f0 Exception (0x00000006541ccc30) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.766 Thread 0x0000025747e837f0 Exception (0x00000006541cce30) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.766 Thread 0x0000025747e837f0 Exception (0x00000006541cde90) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] +Event: 21.767 Thread 0x0000025747e837f0 Exception (0x00000006541ce058) +thrown [s\open\src\hotspot\share\prims\jni.cpp, line 516] + +VM Operations (20 events): +Event: 20.989 Executing VM operation: CollectForMetadataAllocation done +Event: 21.085 Executing VM operation: CollectForMetadataAllocation +Event: 21.085 Executing VM operation: CollectForMetadataAllocation done +Event: 21.113 Executing VM operation: G1Concurrent +Event: 21.154 Executing VM operation: G1Concurrent done +Event: 21.154 Executing VM operation: HandshakeAllThreads +Event: 21.209 Executing VM operation: HandshakeAllThreads done +Event: 21.232 Executing VM operation: HandshakeAllThreads +Event: 21.233 Executing VM operation: HandshakeAllThreads done +Event: 21.239 Executing VM operation: G1Concurrent +Event: 21.242 Executing VM operation: G1Concurrent done +Event: 21.624 Executing VM operation: ICBufferFull +Event: 21.624 Executing VM operation: ICBufferFull done +Event: 21.637 Executing VM operation: G1CollectForAllocation +Event: 21.648 Executing VM operation: G1CollectForAllocation done +Event: 21.701 Executing VM operation: G1CollectForAllocation +Event: 21.713 Executing VM operation: G1CollectForAllocation done +Event: 21.745 Executing VM operation: HandshakeAllThreads +Event: 21.745 Executing VM operation: HandshakeAllThreads done +Event: 21.792 Executing VM operation: G1CollectForAllocation + +Events (20 events): +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575db72390 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575db78210 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575db86710 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575db86c10 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575db9c110 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575db9cd10 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575db9d110 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575db9d710 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575db9f490 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dbb2110 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dbb7010 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dbb7390 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dbe5990 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dc2a290 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dc58490 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dc5b890 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dc5c090 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dc5d090 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dc5e190 +Event: 21.764 Thread 0x000002577ec3aa20 flushing nmethod 0x000002575dc5e910 + + +Dynamic libraries: +0x00007ff7ebc30000 - 0x00007ff7ebc40000 D:\Program Files\Java\jdk-17\bin\java.exe +0x00007ffc3de30000 - 0x00007ffc3e028000 C:\WINDOWS\SYSTEM32\ntdll.dll +0x00007ffc3caf0000 - 0x00007ffc3cbb2000 C:\WINDOWS\System32\KERNEL32.DLL +0x00007ffc3b630000 - 0x00007ffc3b92e000 C:\WINDOWS\System32\KERNELBASE.dll +0x00007ffc3b930000 - 0x00007ffc3ba30000 C:\WINDOWS\System32\ucrtbase.dll +0x00007ffc36620000 - 0x00007ffc3663b000 D:\Program Files\Java\jdk-17\bin\VCRUNTIME140.dll +0x00007ffc2e970000 - 0x00007ffc2e989000 D:\Program Files\Java\jdk-17\bin\jli.dll +0x00007ffc3c010000 - 0x00007ffc3c0c1000 C:\WINDOWS\System32\ADVAPI32.dll +0x00007ffc3c1f0000 - 0x00007ffc3c28e000 C:\WINDOWS\System32\msvcrt.dll +0x00007ffc3cbd0000 - 0x00007ffc3cc6f000 C:\WINDOWS\System32\sechost.dll +0x00007ffc3be50000 - 0x00007ffc3bf73000 C:\WINDOWS\System32\RPCRT4.dll +0x00007ffc3bd60000 - 0x00007ffc3bd87000 C:\WINDOWS\System32\bcrypt.dll +0x00007ffc3c800000 - 0x00007ffc3c99d000 C:\WINDOWS\System32\USER32.dll +0x00007ffc3be20000 - 0x00007ffc3be42000 C:\WINDOWS\System32\win32u.dll +0x00007ffc3bf80000 - 0x00007ffc3bfab000 C:\WINDOWS\System32\GDI32.dll +0x00007ffc3bb80000 - 0x00007ffc3bc97000 C:\WINDOWS\System32\gdi32full.dll +0x00007ffc26790000 - 0x00007ffc26a2a000 C:\WINDOWS\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.19041.4355_none_60b8b9eb71f62e16\COMCTL32.dll +0x00007ffc3ba30000 - 0x00007ffc3bacd000 C:\WINDOWS\System32\msvcp_win.dll +0x00007ffc3afe0000 - 0x00007ffc3afea000 C:\WINDOWS\SYSTEM32\VERSION.dll +0x00007ffc3c0e0000 - 0x00007ffc3c10f000 C:\WINDOWS\System32\IMM32.DLL +0x000000005ca60000 - 0x000000005ca6d000 D:\Program Files (x86)\360\360SAFE\safemon\SafeWrapper.dll +0x00007ffc2e060000 - 0x00007ffc2e165000 D:\Program Files (x86)\360\360SAFE\safemon\libzdtp64.dll +0x00007ffc3cc70000 - 0x00007ffc3d3dd000 C:\WINDOWS\System32\SHELL32.dll +0x00007ffc3c190000 - 0x00007ffc3c1e5000 C:\WINDOWS\System32\SHLWAPI.dll +0x00007ffc36610000 - 0x00007ffc3661c000 D:\Program Files\Java\jdk-17\bin\vcruntime140_1.dll +0x00007ffc03e10000 - 0x00007ffc03e9e000 D:\Program Files\Java\jdk-17\bin\msvcp140.dll +0x00007ffbe4ab0000 - 0x00007ffbe5691000 D:\Program Files\Java\jdk-17\bin\server\jvm.dll +0x00007ffc3c0d0000 - 0x00007ffc3c0d8000 C:\WINDOWS\System32\PSAPI.DLL +0x00007ffc27990000 - 0x00007ffc27999000 C:\WINDOWS\SYSTEM32\WSOCK32.dll +0x00007ffc32310000 - 0x00007ffc32337000 C:\WINDOWS\SYSTEM32\WINMM.dll +0x00007ffc3ca80000 - 0x00007ffc3caeb000 C:\WINDOWS\System32\WS2_32.dll +0x00007ffc39cc0000 - 0x00007ffc39cd2000 C:\WINDOWS\SYSTEM32\kernel.appcore.dll +0x00007ffc2e880000 - 0x00007ffc2e88a000 D:\Program Files\Java\jdk-17\bin\jimage.dll +0x00007ffc397f0000 - 0x00007ffc399d4000 C:\WINDOWS\SYSTEM32\DBGHELP.DLL +0x00007ffc2d790000 - 0x00007ffc2d7c4000 C:\WINDOWS\SYSTEM32\dbgcore.DLL +0x00007ffc3bd90000 - 0x00007ffc3be12000 C:\WINDOWS\System32\bcryptPrimitives.dll +0x00007ffc27490000 - 0x00007ffc2749e000 D:\Program Files\Java\jdk-17\bin\instrument.dll +0x00007ffc27460000 - 0x00007ffc27485000 D:\Program Files\Java\jdk-17\bin\java.dll +0x00007ffbfa7d0000 - 0x00007ffbfa8a7000 D:\Program Files\Java\jdk-17\bin\jsvml.dll +0x00007ffc38f70000 - 0x00007ffc39714000 C:\WINDOWS\SYSTEM32\windows.storage.dll +0x00007ffc3da90000 - 0x00007ffc3dde3000 C:\WINDOWS\System32\combase.dll +0x00007ffc3ae40000 - 0x00007ffc3ae6e000 C:\WINDOWS\SYSTEM32\Wldp.dll +0x00007ffc3d640000 - 0x00007ffc3d70d000 C:\WINDOWS\System32\OLEAUT32.dll +0x00007ffc3d9e0000 - 0x00007ffc3da8d000 C:\WINDOWS\System32\SHCORE.dll +0x00007ffc3b400000 - 0x00007ffc3b424000 C:\WINDOWS\SYSTEM32\profapi.dll +0x00007ffc25b50000 - 0x00007ffc25b68000 D:\Program Files\Java\jdk-17\bin\zip.dll +0x00007ffc25e90000 - 0x00007ffc25ea9000 D:\Program Files\Java\jdk-17\bin\net.dll +0x00007ffc34d20000 - 0x00007ffc34e2d000 C:\WINDOWS\SYSTEM32\WINHTTP.dll +0x00007ffc3aba0000 - 0x00007ffc3ac0a000 C:\WINDOWS\system32\mswsock.dll +0x00007ffc25bd0000 - 0x00007ffc25be6000 D:\Program Files\Java\jdk-17\bin\nio.dll +0x00007ffc25ef0000 - 0x00007ffc25f0a000 D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\bin\breakgen64.dll +0x00007ffc2ccf0000 - 0x00007ffc2cd14000 C:\Users\ADAM5\AppData\Local\Temp\jansi-2.4.1-b87462ac789684e0-jansi.dll +0x00007ffc27a20000 - 0x00007ffc27a30000 D:\Program Files\Java\jdk-17\bin\verify.dll +0x00007ffc3a6e0000 - 0x00007ffc3a713000 C:\WINDOWS\SYSTEM32\ntmarta.dll + +dbghelp: loaded successfully - version: 4.0.5 - missing functions: none +symbol engine: initialized successfully - sym options: 0x614 - pdb path: .;D:\Program Files\Java\jdk-17\bin;C:\WINDOWS\SYSTEM32;C:\WINDOWS\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.19041.4355_none_60b8b9eb71f62e16;D:\Program Files (x86)\360\360SAFE\safemon;D:\Program Files\Java\jdk-17\bin\server;D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\bin;C:\Users\ADAM5\AppData\Local\Temp + +VM Arguments: +jvm_args: -Dmaven.multiModuleProjectDirectory=E:\Idea-project\ikingtec-new6.0\microservices-platform -Djansi.passthrough=true -Dmaven.home=D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\plugins\maven\lib\maven3 -Dclassworlds.conf=D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\plugins\maven\lib\maven3\bin\m2.conf -Dmaven.ext.class.path=D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\plugins\maven\lib\maven-event-listener.jar -javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\lib\idea_rt.jar=58940:D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\bin -Dfile.encoding=UTF-8 +java_command: org.codehaus.classworlds.Launcher -Didea.version=2024.3.1 -T 8 -s D:\maven\apache-maven-3.5.2\conf\settings.xml package +java_class_path (initial): D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\plugins\maven\lib\maven3\boot\plexus-classworlds-2.8.0.jar;D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\plugins\maven\lib\maven3\boot\plexus-classworlds.license +Launcher Type: SUN_STANDARD + +[Global flags] + intx CICompilerCount = 4 {product} {ergonomic} + uint ConcGCThreads = 2 {product} {ergonomic} + uint G1ConcRefinementThreads = 8 {product} {ergonomic} + size_t G1HeapRegionSize = 4194304 {product} {ergonomic} + uintx GCDrainStackTargetSize = 64 {product} {ergonomic} + size_t InitialHeapSize = 536870912 {product} {ergonomic} + size_t MarkStackSize = 4194304 {product} {ergonomic} + size_t MaxHeapSize = 8573157376 {product} {ergonomic} + size_t MaxNewSize = 5142216704 {product} {ergonomic} + size_t MinHeapDeltaBytes = 4194304 {product} {ergonomic} + size_t MinHeapSize = 8388608 {product} {ergonomic} + uintx NonNMethodCodeHeapSize = 5839372 {pd product} {ergonomic} + uintx NonProfiledCodeHeapSize = 122909434 {pd product} {ergonomic} + uintx ProfiledCodeHeapSize = 122909434 {pd product} {ergonomic} + uintx ReservedCodeCacheSize = 251658240 {pd product} {ergonomic} + bool SegmentedCodeCache = true {product} {ergonomic} + size_t SoftMaxHeapSize = 8573157376 {manageable} {ergonomic} + bool UseCompressedClassPointers = true {product lp64_product} {ergonomic} + bool UseCompressedOops = true {product lp64_product} {ergonomic} + bool UseG1GC = true {product} {ergonomic} + bool UseLargePagesIndividualAllocation = false {pd product} {ergonomic} + +Logging: +Log output configuration: + #0: stdout all=warning uptime,level,tags + #1: stderr all=off uptime,level,tags + +Environment Variables: +JAVA_HOME=D:\Program Files\Java\jdk-17 +PATH=C:\Program Files\Common Files\Oracle\Java\javapath;D:\Python39\Scripts\;D:\Python39\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;D:\Program Files\Java\jdk-17\bin;node_global;D:\maven\apache-maven-3.5.2\bin;D:\Program Files\nodejs\node_global\node_modules;E:\gradle\gradle-5.2.1-all\gradle-5.2.1\bin;C:\Users\ADAM5\.windows-build-tools\python27;D:\Program Files (x86)\Yarn\bin\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;node_global;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\Program Files\Microsoft VS Code\bin;D:\P;ogram Files\Git\cmd;C:\Program Files\dotnet\;C:\Program Files\GitHub CLI\;D:\nvm;D:\Program Files\nodejs;D:\Program Files\apache-ant-1.10.15-bin\apache-ant-1.10.15\bin;D:\Program Files (x86)\Tencent\΢ÐÅweb¿ª·¢Õ߹¤¾ß\dll;;;D:\Program Files\Git\cmd;C:\Users\ADAM5\AppData\Local\Microsoft\WindowsApps;D:\Program Files (x86)\SSH Communications Security\SSH Secure Shell;C:\Users\ADAM5\AppData\Roaming\npm;C:\Users\ADAM5\AppData\Local\Yarn\bin;D:\Program Files\JetBrains\PyCharm Community Edition 2020.3.2\bin;C:\Users\ADAM5\AppData\Local\Programs\Fiddler;D:\Program Files (x86)\GitHub CLI\;C:\Users\ADAM5\AppData\Local\Microsoft\WindowsApps;D:\Program Files (x86)\nvm;D:\Program Files\nodejs;D:\Program Files (x86)\Fiddler2\Fiddler;D:\nvm;D:\Program Files\nodejs;D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\bin; +USERNAME=ADAM5 +OS=Windows_NT +PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 158 Stepping 13, GenuineIntel + + + +--------------- S Y S T E M --------------- + +OS: + Windows 10 , 64 bit Build 19041 (10.0.19041.5198) +OS uptime: 6 days 7:35 hours + +CPU: total 8 (initial active 8) (8 cores per cpu, 1 threads per core) family 6 model 158 stepping 13 microcode 0xb8, cx8, cmov, fxsr, mmx, 3dnowpref, sse, sse2, sse3, ssse3, sse4.1, sse4.2, popcnt, lzcnt, tsc, tscinvbit, avx, avx2, aes, erms, clmul, bmi1, bmi2, rtm, adx, fma, vzeroupper, clflush, clflushopt + +Memory: 4k page, system-wide physical 32701M (5698M free) +TotalPageFile size 54576M (AvailPageFile size 117M) +current process WorkingSet (physical memory assigned to process): 1750M, peak: 1755M +current process commit charge ("private bytes"): 1812M, peak: 2516M + +vm_info: Java HotSpot(TM) 64-Bit Server VM (17.0.13+10-LTS-268) for windows-amd64 JRE (17.0.13+10-LTS-268), built on Sep 30 2024 06:33:13 by "mach5one" with MS VC++ 17.6 (VS2022) + +END. diff --git a/hs_err_pid8960.log b/hs_err_pid8960.log new file mode 100644 index 00000000..ba9a3f8c --- /dev/null +++ b/hs_err_pid8960.log @@ -0,0 +1,221 @@ +# +# There is insufficient memory for the Java Runtime Environment to continue. +# Native memory allocation (mmap) failed to map 536870912 bytes for G1 virtual space +# Possible reasons: +# The system is out of physical RAM or swap space +# The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap +# Possible solutions: +# Reduce memory load on the system +# Increase physical memory or swap space +# Check if swap backing store is full +# Decrease Java heap size (-Xmx/-Xms) +# Decrease number of Java threads +# Decrease Java thread stack sizes (-Xss) +# Set larger code cache with -XX:ReservedCodeCacheSize= +# JVM is running with Zero Based Compressed Oops mode in which the Java heap is +# placed in the first 32GB address space. The Java Heap base address is the +# maximum limit for the native heap growth. Please use -XX:HeapBaseMinAddress +# to set the Java Heap base and to place the Java Heap above 32GB virtual address. +# This output file may be truncated or incomplete. +# +# Out of Memory Error (os_windows.cpp:3548), pid=8960, tid=12132 +# +# JRE version: (17.0.13+10) (build ) +# Java VM: Java HotSpot(TM) 64-Bit Server VM (17.0.13+10-LTS-268, mixed mode, emulated-client, sharing, tiered, compressed oops, compressed class ptrs, g1 gc, windows-amd64) +# No core dump will be written. Minidumps are not enabled by default on client versions of Windows +# + +--------------- S U M M A R Y ------------ + +Command Line: -XX:TieredStopAtLevel=1 -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -Dmanagement.endpoints.jmx.exposure.include=* -javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\lib\idea_rt.jar=55248:D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\bin -Dfile.encoding=UTF-8 com.zlt.tourism.CulturalTourismApplication + +Host: Intel(R) Core(TM) i7-9700F CPU @ 3.00GHz, 8 cores, 31G, Windows 10 , 64 bit Build 19041 (10.0.19041.5198) +Time: Sun Jan 5 15:41:20 2025 Windows 10 , 64 bit Build 19041 (10.0.19041.5198) elapsed time: 0.016570 seconds (0d 0h 0m 0s) + +--------------- T H R E A D --------------- + +Current thread (0x000001d97c4e6800): JavaThread "Unknown thread" [_thread_in_vm, id=12132, stack(0x0000004a1ad00000,0x0000004a1ae00000)] + +Stack: [0x0000004a1ad00000,0x0000004a1ae00000] +Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code) +V [jvm.dll+0x67a23a] +V [jvm.dll+0x7da96d] +V [jvm.dll+0x7dc2b3] +V [jvm.dll+0x7dc923] +V [jvm.dll+0x2450ef] +V [jvm.dll+0x677279] +V [jvm.dll+0x66bf22] +V [jvm.dll+0x302006] +V [jvm.dll+0x3095a6] +V [jvm.dll+0x359e9e] +V [jvm.dll+0x35a0cf] +V [jvm.dll+0x2d90d8] +V [jvm.dll+0x2da044] +V [jvm.dll+0x7ace81] +V [jvm.dll+0x367701] +V [jvm.dll+0x78bcc9] +V [jvm.dll+0x3ec9bf] +V [jvm.dll+0x3ee5f1] +C [jli.dll+0x5297] +C [ucrtbase.dll+0x21bb2] +C [KERNEL32.DLL+0x17374] +C [ntdll.dll+0x4cc91] + + +--------------- P R O C E S S --------------- + +Threads class SMR info: +_java_thread_list=0x00007ffbe5568a18, length=0, elements={ +} + +Java Threads: ( => current thread ) + +Other Threads: + 0x000001d97c554a50 GCTaskThread "GC Thread#0" [stack: 0x0000004a1ae00000,0x0000004a1af00000] [id=3964] + 0x000001d97c565820 ConcurrentGCThread "G1 Main Marker" [stack: 0x0000004a1af00000,0x0000004a1b000000] [id=28228] + 0x000001d97c5668d0 ConcurrentGCThread "G1 Conc#0" [stack: 0x0000004a1b000000,0x0000004a1b100000] [id=4148] + +[error occurred during error reporting (printing all threads), id 0xc0000005, EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffbe4d99bc7] + +VM state: not at safepoint (not fully initialized) + +VM Mutex/Monitor currently owned by a thread: ([mutex/lock_event]) +[0x000001d97c4e37c0] Heap_lock - owner thread: 0x000001d97c4e6800 + +Heap address: 0x0000000601000000, size: 8176 MB, Compressed Oops mode: Zero based, Oop shift amount: 3 + +CDS archive(s) mapped at: [0x0000000000000000-0x0000000000000000-0x0000000000000000), size 0, SharedBaseAddress: 0x0000000800000000, ArchiveRelocationMode: 1. +Narrow klass base: 0x0000000000000000, Narrow klass shift: 0, Narrow klass range: 0x0 + +GC Precious Log: + + +Heap: + garbage-first heap total 0K, used 0K [0x0000000601000000, 0x0000000800000000) + region size 4096K, 0 young (0K), 0 survivors (0K) + +[error occurred during error reporting (printing heap information), id 0xc0000005, EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffbe5183a29] + +GC Heap History (0 events): +No events + +Deoptimization events (0 events): +No events + +Classes unloaded (0 events): +No events + +Classes redefined (0 events): +No events + +Internal exceptions (0 events): +No events + +VM Operations (0 events): +No events + +Events (1 events): +Event: 0.011 Loaded shared library D:\Program Files\Java\jdk-17\bin\java.dll + + +Dynamic libraries: +0x00007ff7ebc30000 - 0x00007ff7ebc40000 D:\Program Files\Java\jdk-17\bin\java.exe +0x00007ffc3de30000 - 0x00007ffc3e028000 C:\WINDOWS\SYSTEM32\ntdll.dll +0x00007ffc3caf0000 - 0x00007ffc3cbb2000 C:\WINDOWS\System32\KERNEL32.DLL +0x00007ffc3b630000 - 0x00007ffc3b92e000 C:\WINDOWS\System32\KERNELBASE.dll +0x00007ffc3b930000 - 0x00007ffc3ba30000 C:\WINDOWS\System32\ucrtbase.dll +0x00007ffc36620000 - 0x00007ffc3663b000 D:\Program Files\Java\jdk-17\bin\VCRUNTIME140.dll +0x00007ffc2e970000 - 0x00007ffc2e989000 D:\Program Files\Java\jdk-17\bin\jli.dll +0x00007ffc3c010000 - 0x00007ffc3c0c1000 C:\WINDOWS\System32\ADVAPI32.dll +0x00007ffc3c1f0000 - 0x00007ffc3c28e000 C:\WINDOWS\System32\msvcrt.dll +0x00007ffc3cbd0000 - 0x00007ffc3cc6f000 C:\WINDOWS\System32\sechost.dll +0x00007ffc3be50000 - 0x00007ffc3bf73000 C:\WINDOWS\System32\RPCRT4.dll +0x00007ffc3bd60000 - 0x00007ffc3bd87000 C:\WINDOWS\System32\bcrypt.dll +0x00007ffc3c800000 - 0x00007ffc3c99d000 C:\WINDOWS\System32\USER32.dll +0x00007ffc3be20000 - 0x00007ffc3be42000 C:\WINDOWS\System32\win32u.dll +0x00007ffc3bf80000 - 0x00007ffc3bfab000 C:\WINDOWS\System32\GDI32.dll +0x00007ffc3bb80000 - 0x00007ffc3bc97000 C:\WINDOWS\System32\gdi32full.dll +0x00007ffc26790000 - 0x00007ffc26a2a000 C:\WINDOWS\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.19041.4355_none_60b8b9eb71f62e16\COMCTL32.dll +0x00007ffc3ba30000 - 0x00007ffc3bacd000 C:\WINDOWS\System32\msvcp_win.dll +0x00007ffc3afe0000 - 0x00007ffc3afea000 C:\WINDOWS\SYSTEM32\VERSION.dll +0x00007ffc3c0e0000 - 0x00007ffc3c10f000 C:\WINDOWS\System32\IMM32.DLL +0x000000005ca60000 - 0x000000005ca6d000 D:\Program Files (x86)\360\360SAFE\safemon\SafeWrapper.dll +0x00007ffc2e060000 - 0x00007ffc2e165000 D:\Program Files (x86)\360\360SAFE\safemon\libzdtp64.dll +0x00007ffc3cc70000 - 0x00007ffc3d3dd000 C:\WINDOWS\System32\SHELL32.dll +0x00007ffc3c190000 - 0x00007ffc3c1e5000 C:\WINDOWS\System32\SHLWAPI.dll +0x00007ffc36610000 - 0x00007ffc3661c000 D:\Program Files\Java\jdk-17\bin\vcruntime140_1.dll +0x00007ffc03e10000 - 0x00007ffc03e9e000 D:\Program Files\Java\jdk-17\bin\msvcp140.dll +0x00007ffbe4ab0000 - 0x00007ffbe5691000 D:\Program Files\Java\jdk-17\bin\server\jvm.dll +0x00007ffc3c0d0000 - 0x00007ffc3c0d8000 C:\WINDOWS\System32\PSAPI.DLL +0x00007ffc32310000 - 0x00007ffc32337000 C:\WINDOWS\SYSTEM32\WINMM.dll +0x00007ffc27990000 - 0x00007ffc27999000 C:\WINDOWS\SYSTEM32\WSOCK32.dll +0x00007ffc3ca80000 - 0x00007ffc3caeb000 C:\WINDOWS\System32\WS2_32.dll +0x00007ffc39cc0000 - 0x00007ffc39cd2000 C:\WINDOWS\SYSTEM32\kernel.appcore.dll +0x00007ffc2e880000 - 0x00007ffc2e88a000 D:\Program Files\Java\jdk-17\bin\jimage.dll +0x00007ffc397f0000 - 0x00007ffc399d4000 C:\WINDOWS\SYSTEM32\DBGHELP.DLL +0x00007ffc2d790000 - 0x00007ffc2d7c4000 C:\WINDOWS\SYSTEM32\dbgcore.DLL +0x00007ffc3bd90000 - 0x00007ffc3be12000 C:\WINDOWS\System32\bcryptPrimitives.dll +0x00007ffc27490000 - 0x00007ffc2749e000 D:\Program Files\Java\jdk-17\bin\instrument.dll +0x00007ffc27460000 - 0x00007ffc27485000 D:\Program Files\Java\jdk-17\bin\java.dll + +dbghelp: loaded successfully - version: 4.0.5 - missing functions: none +symbol engine: initialized successfully - sym options: 0x614 - pdb path: .;D:\Program Files\Java\jdk-17\bin;C:\WINDOWS\SYSTEM32;C:\WINDOWS\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.19041.4355_none_60b8b9eb71f62e16;D:\Program Files (x86)\360\360SAFE\safemon;D:\Program Files\Java\jdk-17\bin\server + +VM Arguments: +jvm_args: -XX:TieredStopAtLevel=1 -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -Dmanagement.endpoints.jmx.exposure.include=* -javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\lib\idea_rt.jar=55248:D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\bin -Dfile.encoding=UTF-8 +java_command: com.zlt.tourism.CulturalTourismApplication +java_class_path (initial): E:\Idea-project\ikingtec-new6.0\microservices-platform\zlt-business\tourism-center\tourism-service\target\classes;E:\Idea-project\ikingtec-new6.0\microservices-platform\zlt-business\tourism-center\tourism-core\target\classes;D:\maven\ikingtec-repo\com\github\pagehelper\pagehelper-spring-boot-starter\1.4.6\pagehelper-spring-boot-starter-1.4.6.jar;D:\maven\ikingtec-repo\org\mybatis\spring\boot\mybatis-spring-boot-starter\2.2.2\mybatis-spring-boot-starter-2.2.2.jar;D:\maven\ikingtec-repo\org\mybatis\spring\boot\mybatis-spring-boot-autoconfigure\2.2.2\mybatis-spring-boot-autoconfigure-2.2.2.jar;D:\maven\ikingtec-repo\com\github\pagehelper\pagehelper-spring-boot-autoconfigure\1.4.6\pagehelper-spring-boot-autoconfigure-1.4.6.jar;D:\maven\ikingtec-repo\com\github\pagehelper\pagehelper\5.3.2\pagehelper-5.3.2.jar;D:\maven\ikingtec-repo\org\springframework\statemachine\spring-statemachine-core\2.5.1\spring-statemachine-core-2.5.1.jar;D:\maven\ikingtec-repo\org\springframework\spring-tx\6.0.14\spring-tx-6.0.14.jar;D:\maven\ikingtec-repo\org\springframework\spring-messaging\6.0.14\spring-messaging-6.0.14.jar;D:\maven\ikingtec-repo\javax\servlet\javax.servlet-api\3.1.0\javax.servlet-api-3.1.0.jar;D:\maven\ikingtec-repo\com\alibaba\fastjson\1.2.83\fastjson-1.2.83.jar;E:\Idea-project\ikingtec-new6.0\microservices-platform\zlt-config\target\classes;D:\maven\ikingtec-repo\com\alibaba\cloud\spring-cloud-starter-alibaba-nacos-config\2022.0.0.0\spring-cloud-starter-alibaba-nacos-config-2022.0.0.0.jar;D:\maven\ikingtec-repo\org\slf4j\slf4j-api\2.0.9\slf4j-api-2.0.9.jar;D:\maven\ikingtec-repo\jakarta\annotation\jakarta.annotation-api\2.1.1\jakarta.annotation-api-2.1.1.jar;E:\Idea-project\ikingtec-new6.0\microservices-platform\zlt-commons\zlt-common-spring-boot-starter\target\classes;E:\Idea-project\ikingtec-new6.0\microservices-platform\zlt-commons\zlt-common-core\target\classes;D:\maven\ikingtec-repo\com\baomidou\mybatis-plus-extension\3.5.4.1\mybatis-plus-e +Launcher Type: SUN_STANDARD + +[Global flags] + intx CICompilerCount = 4 {product} {ergonomic} + uint ConcGCThreads = 2 {product} {ergonomic} + uint G1ConcRefinementThreads = 8 {product} {ergonomic} + size_t G1HeapRegionSize = 4194304 {product} {ergonomic} + uintx GCDrainStackTargetSize = 64 {product} {ergonomic} + size_t InitialHeapSize = 536870912 {product} {ergonomic} + bool ManagementServer = true {product} {command line} + size_t MarkStackSize = 4194304 {product} {ergonomic} + size_t MaxHeapSize = 8573157376 {product} {ergonomic} + size_t MinHeapDeltaBytes = 4194304 {product} {ergonomic} + size_t MinHeapSize = 8388608 {product} {ergonomic} + uintx NonProfiledCodeHeapSize = 0 {pd product} {ergonomic} + bool ProfileInterpreter = false {pd product} {command line} + uintx ProfiledCodeHeapSize = 0 {pd product} {ergonomic} + size_t SoftMaxHeapSize = 8573157376 {manageable} {ergonomic} + intx TieredStopAtLevel = 1 {product} {command line} + bool UseCompressedClassPointers = true {product lp64_product} {ergonomic} + bool UseCompressedOops = true {product lp64_product} {ergonomic} + bool UseG1GC = true {product} {ergonomic} + bool UseLargePagesIndividualAllocation = false {pd product} {ergonomic} + +Logging: +Log output configuration: + #0: stdout all=warning uptime,level,tags + #1: stderr all=off uptime,level,tags + +Environment Variables: +JAVA_HOME=D:\Program Files\Java\jdk-17 +PATH=C:\Program Files\Common Files\Oracle\Java\javapath;D:\Python39\Scripts\;D:\Python39\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;D:\Program Files\Java\jdk-17\bin;node_global;D:\maven\apache-maven-3.5.2\bin;D:\Program Files\nodejs\node_global\node_modules;E:\gradle\gradle-5.2.1-all\gradle-5.2.1\bin;C:\Users\ADAM5\.windows-build-tools\python27;D:\Program Files (x86)\Yarn\bin\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;node_global;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\Program Files\Microsoft VS Code\bin;D:\P;ogram Files\Git\cmd;C:\Program Files\dotnet\;C:\Program Files\GitHub CLI\;D:\nvm;D:\Program Files\nodejs;D:\Program Files\apache-ant-1.10.15-bin\apache-ant-1.10.15\bin;D:\Program Files (x86)\Tencent\΢ÐÅweb¿ª·¢Õ߹¤¾ß\dll;;;D:\Program Files\Git\cmd;C:\Users\ADAM5\AppData\Local\Microsoft\WindowsApps;D:\Program Files (x86)\SSH Communications Security\SSH Secure Shell;C:\Users\ADAM5\AppData\Roaming\npm;C:\Users\ADAM5\AppData\Local\Yarn\bin;D:\Program Files\JetBrains\PyCharm Community Edition 2020.3.2\bin;C:\Users\ADAM5\AppData\Local\Programs\Fiddler;D:\Program Files (x86)\GitHub CLI\;C:\Users\ADAM5\AppData\Local\Microsoft\WindowsApps;D:\Program Files (x86)\nvm;D:\Program Files\nodejs;D:\Program Files (x86)\Fiddler2\Fiddler;D:\nvm;D:\Program Files\nodejs;D:\Program Files\JetBrains\IntelliJ IDEA 2024.3.1\bin; +USERNAME=ADAM5 +OS=Windows_NT +PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 158 Stepping 13, GenuineIntel + + + +--------------- S Y S T E M --------------- + +OS: + Windows 10 , 64 bit Build 19041 (10.0.19041.5198) +OS uptime: 6 days 20:09 hours + +CPU: total 8 (initial active 8) (8 cores per cpu, 1 threads per core) family 6 model 158 stepping 13 microcode 0xb8, cx8, cmov, fxsr, mmx, 3dnowpref, sse, sse2, sse3, ssse3, sse4.1, sse4.2, popcnt, lzcnt, tsc, tscinvbit, avx, avx2, aes, erms, clmul, bmi1, bmi2, rtm, adx, fma, vzeroupper, clflush, clflushopt + +Memory: 4k page, system-wide physical 32701M (6439M free) +TotalPageFile size 54576M (AvailPageFile size 25M) +current process WorkingSet (physical memory assigned to process): 12M, peak: 12M +current process commit charge ("private bytes"): 56M, peak: 568M + +vm_info: Java HotSpot(TM) 64-Bit Server VM (17.0.13+10-LTS-268) for windows-amd64 JRE (17.0.13+10-LTS-268), built on Sep 30 2024 06:33:13 by "mach5one" with MS VC++ 17.6 (VS2022) + +END. diff --git a/pom.xml b/pom.xml index 770f66a8..aa79d001 100644 --- a/pom.xml +++ b/pom.xml @@ -60,6 +60,11 @@ 10.1.11 5.2.1 11.7 + 1.3.1 + 4.9.1 + 2.3.3 + 2.3.0 + 3.3.3 @@ -102,6 +107,12 @@ tomcat-embed-core ${tomcat-embed-core.version} + + + com.alibaba + easyexcel + ${easyexcel.version} + @@ -392,6 +403,16 @@ oauth2-oidc-sdk ${oauth2-oidc-sdk.version} + + com.zlt + zlt-wechat-common-core + ${project.version} + + + com.zlt + zlt-wechat-spring-boot-starter + ${project.version} + @@ -471,7 +492,7 @@ zlt-config - zlt-demo + diff --git a/structure.txt b/structure.txt new file mode 100644 index 00000000..d2123b66 Binary files /dev/null and b/structure.txt differ diff --git a/zlt-business/code-generator/src/main/java/com/central/generator/CodeGeneratorApp.java b/zlt-business/code-generator/src/main/java/com/central/generator/CodeGeneratorApp.java index 5c48b0a4..269f36f2 100644 --- a/zlt-business/code-generator/src/main/java/com/central/generator/CodeGeneratorApp.java +++ b/zlt-business/code-generator/src/main/java/com/central/generator/CodeGeneratorApp.java @@ -9,7 +9,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients; * @author zlt */ @EnableDiscoveryClient -@EnableFeignClients(basePackages = "com.central") +@EnableFeignClients(basePackages = "com.central.generator") @SpringBootApplication public class CodeGeneratorApp { public static void main(String[] args) { diff --git a/zlt-business/code-generator/src/main/java/com/central/generator/mapper/SysGeneratorMapper.java b/zlt-business/code-generator/src/main/java/com/central/generator/mapper/SysGeneratorMapper.java index 3eae9d96..a6ba6984 100644 --- a/zlt-business/code-generator/src/main/java/com/central/generator/mapper/SysGeneratorMapper.java +++ b/zlt-business/code-generator/src/main/java/com/central/generator/mapper/SysGeneratorMapper.java @@ -2,6 +2,7 @@ package com.central.generator.mapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.central.db.mapper.SuperMapper; +import com.central.generator.model.TableEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; @@ -14,7 +15,7 @@ import java.util.Map; */ @Component @Mapper -public interface SysGeneratorMapper extends SuperMapper { +public interface SysGeneratorMapper extends SuperMapper { List> queryList(Page> page, @Param("p") Map map); int queryTotal(Map map); diff --git a/zlt-business/code-generator/src/main/java/com/central/generator/service/SysGeneratorService.java b/zlt-business/code-generator/src/main/java/com/central/generator/service/SysGeneratorService.java index ad7a7391..bedf1e44 100644 --- a/zlt-business/code-generator/src/main/java/com/central/generator/service/SysGeneratorService.java +++ b/zlt-business/code-generator/src/main/java/com/central/generator/service/SysGeneratorService.java @@ -1,17 +1,16 @@ package com.central.generator.service; +import com.baomidou.mybatisplus.extension.service.IService; +import com.central.common.model.PageResult; +import com.central.generator.model.TableEntity; + import java.util.List; import java.util.Map; -import com.baomidou.mybatisplus.extension.service.IService; -import com.central.common.model.PageResult; -import org.springframework.stereotype.Service; - /** * @Author zlt */ -@Service -public interface SysGeneratorService extends IService { +public interface SysGeneratorService extends IService { PageResult queryList(Map map); Map queryTable(String tableName); diff --git a/zlt-business/code-generator/src/main/java/com/central/generator/service/impl/SysGeneratorServiceImpl.java b/zlt-business/code-generator/src/main/java/com/central/generator/service/impl/SysGeneratorServiceImpl.java index c194703d..990453f5 100644 --- a/zlt-business/code-generator/src/main/java/com/central/generator/service/impl/SysGeneratorServiceImpl.java +++ b/zlt-business/code-generator/src/main/java/com/central/generator/service/impl/SysGeneratorServiceImpl.java @@ -1,15 +1,10 @@ package com.central.generator.service.impl; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.zip.ZipOutputStream; - import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.central.common.model.PageResult; import com.central.generator.mapper.SysGeneratorMapper; +import com.central.generator.model.TableEntity; import com.central.generator.service.SysGeneratorService; import com.central.generator.utils.GenUtils; import lombok.extern.slf4j.Slf4j; @@ -17,12 +12,18 @@ import org.apache.commons.collections4.MapUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipOutputStream; + /** * @Author zlt */ @Slf4j @Service -public class SysGeneratorServiceImpl extends ServiceImpl implements SysGeneratorService { +public class SysGeneratorServiceImpl extends ServiceImpl implements SysGeneratorService { @Autowired private SysGeneratorMapper sysGeneratorMapper; @@ -31,7 +32,7 @@ public class SysGeneratorServiceImpl extends ServiceImpl implements SysGenerator Page> page = new Page<>(MapUtils.getInteger(map, "page"), MapUtils.getInteger(map, "limit")); List> list = sysGeneratorMapper.queryList(page, map); - return PageResult.>builder().data(list).code(0).count(page.getTotal()).build(); + return PageResult.>builder().data(list).resp_code(0).count(page.getTotal()).build(); } @Override @@ -63,4 +64,5 @@ public class SysGeneratorServiceImpl extends ServiceImpl implements SysGenerator } return outputStream.toByteArray(); } + } diff --git a/zlt-business/code-generator/src/main/resources/application.yml b/zlt-business/code-generator/src/main/resources/application.yml index 3f985645..5af2c366 100644 --- a/zlt-business/code-generator/src/main/resources/application.yml +++ b/zlt-business/code-generator/src/main/resources/application.yml @@ -1,6 +1,6 @@ spring: datasource: - url: jdbc:mysql://${zlt.datasource.ip}:3306/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + url: jdbc:mysql://${zlt.datasource.ip}/order-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: ${zlt.datasource.username} password: ${zlt.datasource.password} driver-class-name: com.mysql.cj.jdbc.Driver @@ -19,4 +19,4 @@ springdoc: knife4j: enable: true setting: - swagger-model-name: 代码生成器接口文档 \ No newline at end of file + swagger-model-name: 代码生成器接口文档 diff --git a/zlt-business/code-generator/src/main/resources/generator.properties b/zlt-business/code-generator/src/main/resources/generator.properties index 2bf5e525..b23544ed 100644 --- a/zlt-business/code-generator/src/main/resources/generator.properties +++ b/zlt-business/code-generator/src/main/resources/generator.properties @@ -1,9 +1,9 @@ #包前缀 package=com.central #模块名,生成的类的package为:com.central.generator -moduleName=generator +moduleName=tourist #作者名 -author=zlt +author=lsl #Email email= #表前缀,如表tb_sys_user 生成类 sys_user @@ -30,4 +30,4 @@ longtext=String date=Date datetime=Date -timestamp=Date \ No newline at end of file +timestamp=Date diff --git a/zlt-business/device-center/pom.xml b/zlt-business/device-center/pom.xml new file mode 100644 index 00000000..4631efb4 --- /dev/null +++ b/zlt-business/device-center/pom.xml @@ -0,0 +1,146 @@ + + + 4.0.0 + + com.zlt + zlt-business + 6.0.0 + + + device-center + 设备中心 + + + 17 + 17 + UTF-8 + + + + + + com.zlt + zlt-config + + + com.zlt + zlt-log-spring-boot-starter + + + com.zlt + zlt-common-spring-boot-starter + + + com.zlt + zlt-db-spring-boot-starter + + + com.zlt + zlt-redis-spring-boot-starter + + + com.zlt + zlt-loadbalancer-spring-boot-starter + + + com.zlt + zlt-sentinel-spring-boot-starter + + + + com.github.xiaoymin + knife4j-openapi3-jakarta-spring-boot-starter + + + com.zlt + search-client + + + + org.springframework.boot + spring-boot-starter-web + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.boot + spring-boot-starter-actuator + + + + mysql + mysql-connector-java + + + + io.micrometer + micrometer-registry-prometheus + + + junit + junit + test + + + org.hibernate + hibernate-validator + + + + org.springframework.boot + spring-boot-starter-validation + + + cn.hutool + hutool-all + 5.8.25 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + com.spotify + docker-maven-plugin + + ${docker.image.prefix}/${project.artifactId} + + ${project.version} + latest + + true + ${docker.baseImage} + ${docker.volumes} + + ${docker.java.opts} + + ["sh","-c","java $JAVA_OPTS ${docker.java.security.egd} -jar /${project.build.finalName}.jar"] + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + ${project.artifactId} + + diff --git a/zlt-business/device-center/src/main/java/com/central/device/DeviceCenterApp.java b/zlt-business/device-center/src/main/java/com/central/device/DeviceCenterApp.java new file mode 100644 index 00000000..332428f6 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/DeviceCenterApp.java @@ -0,0 +1,22 @@ +package com.central.device; + +import com.central.common.lb.annotation.EnableFeignInterceptor; +import com.central.search.annotation.EnableSearchClient; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * @author 作者 lsl E-mail: 1272745473@qq.com + */ +@EnableDiscoveryClient +@EnableSearchClient +@EnableTransactionManagement +@EnableFeignInterceptor +@SpringBootApplication +public class DeviceCenterApp { + public static void main(String[] args) { + SpringApplication.run(DeviceCenterApp.class, args); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceController.java new file mode 100644 index 00000000..954ecc12 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceController.java @@ -0,0 +1,273 @@ +package com.central.device.controller; + +import cn.hutool.core.collection.CollUtil; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.support.ExcelTypeEnum; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.device.model.AgeDevice; +import com.central.device.model.excel.AgeDeviceExcel; +import com.central.device.service.IAgeDeviceService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@RequestMapping("/device") +@Tag(name = "设备管理") +@RequiredArgsConstructor +public class AgeDeviceController { + + + @Autowired + private IAgeDeviceService ageDeviceService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDeviceService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDevice model = ageDeviceService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDevice ageDevice) { + ageDeviceService.saveOrUpdate(ageDevice); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDeviceService.removeById(id); + return Result.succeed("删除成功"); + } + + /** + * 导出设备信息 + */ + @Operation(summary = "导出设备信息") + @PostMapping("/export") + public void exportDevices(@RequestBody Map params, HttpServletResponse response) { + try { + // 设置响应头 + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + String fileName = URLEncoder.encode("设备信息", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20"); + response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); + + // 查询导出数据 + List deviceList = ageDeviceService.findListByParams(params); + if (CollUtil.isEmpty(deviceList)) { + deviceList = new ArrayList<>(); + } + + // 转换并写入Excel + List excelList = deviceList.stream() + .map(AgeDeviceExcel::fromDevice) + .collect(java.util.stream.Collectors.toList()); + + EasyExcel.write(response.getOutputStream(), AgeDeviceExcel.class) + .excelType(ExcelTypeEnum.XLSX) + .sheet("设备信息") + .doWrite(excelList); + + } catch (Exception e) { + log.error("导出设备信息失败", e); + // 重置response + response.reset(); + response.setContentType("application/json"); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + try { + response.getWriter().println("{\"code\":500,\"msg\":\"导出失败\"}"); + } catch (IOException ex) { + log.error("写入响应失败", ex); + } + } + } + + /** + * 导入设备信息 + */ + @Operation(summary = "导入设备信息") + @PostMapping("/import") + public Result importDevices(@RequestParam("file") MultipartFile file) { + try { + if (file.isEmpty()) { + return Result.failed("请选择要导入的文件"); + } + + // 文件大小校验(10MB) + if (file.getSize() > 10 * 1024 * 1024) { + return Result.failed("文件大小不能超过10MB"); + } + + // 文件类型校验 + String fileName = file.getOriginalFilename(); + if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) { + return Result.failed("请上传Excel文件"); + } + + // 读取Excel数据 + List excelList = EasyExcel.read(file.getInputStream()) + .head(AgeDeviceExcel.class) + .sheet() + .doReadSync(); + + if (CollUtil.isEmpty(excelList)) { + return Result.failed("导入数据为空"); + } + + // 数据校验和转换 + List errorMsgs = new ArrayList<>(); + List deviceList = new ArrayList<>(); + + for (int i = 0; i < excelList.size(); i++) { + AgeDeviceExcel excelData = excelList.get(i); + try { + // 数据校验 + validateExcelData(excelData, i + 1, errorMsgs); + if (errorMsgs.isEmpty()) { + deviceList.add(excelData.toDevice()); + } + } catch (Exception e) { + log.error("第{}行数据处理失败", i + 1, e); + errorMsgs.add(String.format("第%d行数据处理失败:%s", i + 1, e.getMessage())); + } + } + + if (!errorMsgs.isEmpty()) { + return Result.failed("导入失败:" + String.join("; ", errorMsgs)); + } + + // 批量保存数据 + boolean success = ageDeviceService.importDevices(deviceList); + return success ? Result.succeed("导入成功") : Result.failed("导入失败"); + + } catch (Exception e) { + log.error("导入设备信息失败", e); + return Result.failed("导入失败:" + e.getMessage()); + } + } + + @Operation(summary = "下载导入模板") + @GetMapping("/template") + public void downloadTemplate(HttpServletResponse response) { + try { + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + String fileName = URLEncoder.encode("设备导入模板", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20"); + response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); + + // 创建模板数据 + List templateList = new ArrayList<>(); + // 可以添加一行示例数据 + AgeDeviceExcel template = new AgeDeviceExcel(); + template.setDeviceSn("示例:DEVICE001"); + template.setDeviceName("示例:测试设备1"); + templateList.add(template); + + EasyExcel.write(response.getOutputStream(), AgeDeviceExcel.class) + .excelType(ExcelTypeEnum.XLSX) + .sheet("设备信息") + .doWrite(templateList); + + } catch (Exception e) { + log.error("下载模板失败", e); + response.reset(); + response.setContentType("application/json"); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + try { + response.getWriter().println("{\"code\":500,\"msg\":\"下载模板失败\"}"); + } catch (IOException ex) { + log.error("写入响应失败", ex); + } + } + } + + /** + * 验证Excel数据 + */ + private void validateExcelData(AgeDeviceExcel excelData, int rowIndex, List errorMsgs) { + if (excelData == null) { + errorMsgs.add(String.format("第%d行数据为空", rowIndex)); + return; + } + + // 必填字段校验 + if (org.springframework.util.StringUtils.isEmpty(excelData.getDeviceSn())) { + errorMsgs.add(String.format("第%d行:设备序列号不能为空", rowIndex)); + } + if (org.springframework.util.StringUtils.isEmpty(excelData.getDeviceName())) { + errorMsgs.add(String.format("第%d行:设备名称不能为空", rowIndex)); + } + + // 字段格式校验 + if (excelData.getDeviceType() != null && (excelData.getDeviceType() < 0 || excelData.getDeviceType() > 100)) { + errorMsgs.add(String.format("第%d行:设备类型取值范围为0-100", rowIndex)); + } + + // 重复性校验 + if (!org.springframework.util.StringUtils.isEmpty(excelData.getDeviceSn())) { + boolean exists = ageDeviceService.checkDeviceSnExists(excelData.getDeviceSn()); + if (exists) { + errorMsgs.add(String.format("第%d行:设备序列号已存在", rowIndex)); + } + } + } + + private List convertToExcelList(List deviceList) { + return deviceList.stream().map(device -> { + AgeDeviceExcel excel = new AgeDeviceExcel(); + BeanUtils.copyProperties(device, excel); + return excel; + }).collect(Collectors.toList()); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java new file mode 100644 index 00000000..b317657e --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceFirmwareController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeDeviceFirmware; +import com.central.device.service.IAgeDeviceFirmwareService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@RestController +@RequestMapping("/firmware") +@Tag(name = "Firmware file information") +@RequiredArgsConstructor +public class AgeDeviceFirmwareController { + private final IAgeDeviceFirmwareService ageDeviceFirmwareService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDeviceFirmwareService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDeviceFirmware model = ageDeviceFirmwareService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDeviceFirmware ageDeviceFirmware) { + ageDeviceFirmwareService.saveOrUpdate(ageDeviceFirmware); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDeviceFirmwareService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java new file mode 100644 index 00000000..0c0e4cd6 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceHmsController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeDeviceHms; +import com.central.device.service.IAgeDeviceHmsService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +@Slf4j +@RestController +@RequestMapping("/hms") +@Tag(name = "Device's hms information") +@RequiredArgsConstructor +public class AgeDeviceHmsController { + private final IAgeDeviceHmsService ageDeviceHmsService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDeviceHmsService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDeviceHms model = ageDeviceHmsService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDeviceHms ageDeviceHms) { + ageDeviceHmsService.saveOrUpdate(ageDeviceHms); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDeviceHmsService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java new file mode 100644 index 00000000..8526c968 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceLogsController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeDeviceLogs; +import com.central.device.service.IAgeDeviceLogsService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +@Slf4j +@RestController +@RequestMapping("/logs") +@Tag(name = "Log for uploading logs") +@RequiredArgsConstructor +public class AgeDeviceLogsController { + private final IAgeDeviceLogsService ageDeviceLogsService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDeviceLogsService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDeviceLogs model = ageDeviceLogsService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDeviceLogs ageDeviceLogs) { + ageDeviceLogsService.saveOrUpdate(ageDeviceLogs); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDeviceLogsService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java new file mode 100644 index 00000000..2bc7f5fa --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeDevicePayloadController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeDevicePayload; +import com.central.device.service.IAgeDevicePayloadService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +@Slf4j +@RestController +@RequestMapping("/payload") +@Tag(name = "The payload information of the device.") +@RequiredArgsConstructor +public class AgeDevicePayloadController { + private final IAgeDevicePayloadService ageDevicePayloadService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageDevicePayloadService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeDevicePayload model = ageDevicePayloadService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeDevicePayload ageDevicePayload) { + ageDevicePayloadService.saveOrUpdate(ageDevicePayload); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageDevicePayloadService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java new file mode 100644 index 00000000..54c3446b --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeFirmwareModelController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeFirmwareModel; +import com.central.device.service.IAgeFirmwareModelService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +@Slf4j +@RestController +@RequestMapping("/firmware/model") +@Tag(name = "") +@RequiredArgsConstructor +public class AgeFirmwareModelController { + private final IAgeFirmwareModelService ageFirmwareModelService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageFirmwareModelService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeFirmwareModel model = ageFirmwareModelService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeFirmwareModel ageFirmwareModel) { + ageFirmwareModelService.saveOrUpdate(ageFirmwareModel); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageFirmwareModelService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java new file mode 100644 index 00000000..56c9e747 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/AgeWorkspaceController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.AgeWorkspace; +import com.central.device.service.IAgeWorkspaceService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +@Slf4j +@RestController +@RequestMapping("/workspace") +@Tag(name = "") +@RequiredArgsConstructor +public class AgeWorkspaceController { + private final IAgeWorkspaceService ageWorkspaceService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return ageWorkspaceService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + AgeWorkspace model = ageWorkspaceService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody AgeWorkspace ageWorkspace) { + ageWorkspaceService.saveOrUpdate(ageWorkspace); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + ageWorkspaceService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/ApiDeviceController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/ApiDeviceController.java new file mode 100644 index 00000000..58009253 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/ApiDeviceController.java @@ -0,0 +1,174 @@ +package com.central.device.controller; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.nacos.shaded.com.google.gson.Gson; +import com.alibaba.nacos.shaded.com.google.gson.JsonElement; +import com.alibaba.nacos.shaded.com.google.gson.JsonObject; +import com.central.common.model.Result; +import com.central.device.feign.OrderCenterService; +import com.central.device.message.ControlEnum; +import com.central.device.message.ControlMessageConstant; +import com.central.device.model.LineFile; +import com.central.device.service.ILineFileService; +import com.central.device.service.LiveStreamService; +import com.central.device.util.IotRequestResult; +import com.central.device.util.MapUtil; +import com.central.device.util.RequestUtils; +import com.fasterxml.jackson.core.JsonProcessingException; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * 设备操作controller + * @author lishilin + * @date 2024-12-31 + */ +@Tag(name = "MQTT设备管理") +@Slf4j +@RestController +public class ApiDeviceController { + + @Value("${jetlinks.server.baseUrl}") + private String baseUrl;// = "http://119.45.169.13:8848/"; + + @Autowired + private LiveStreamService liveStreamService; + + @Autowired + private RequestUtils requestUtils; + + private ControlMessageConstant controlMessageConstant = new ControlMessageConstant(); + + @Autowired + private OrderCenterService orderCenterService; + + @Autowired + private ILineFileService lineFileService; + /** + * 获取设备属性 + */ + @Operation(summary = "获取设备属性") + @GetMapping("/property/_query/{deviceId}/{property}") + public Result getProperty(@RequestParam Map param,@PathVariable("deviceId") String deviceId) throws IOException { + + //温度属性,属性在设备管理的设备型号中设置 + String property = MapUtil.getStrValue(param, "property"); + String url = baseUrl + "/device/" + deviceId + "/property/" + property; + + Map result = requestUtils.getGetRequestResultMap(url,new HashMap<>()); + return Result.succeed(result,"查询成功"); + + + } + + /** + * 设置设备属性测试 + */ + @Operation(summary = "设备属性设置") + @PostMapping("/setting/{deviceId}/property") + public Result writeProperties(@RequestBody Map param, @PathVariable("deviceId") String deviceId) { + log.info("开始设置设备属性: deviceId={}, param={}", deviceId, param); + try { + // 1. 参数校验 + String control = MapUtil.getStrValue(param, "control"); + String orderNo = MapUtil.getStrValue(param, "order_no"); + if (!validateParams(control, orderNo)) { + return Result.failed("参数错误"); + } + + // 2. 检查订单状态 + String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo); + if (!isValidOrderStatus(orderStatus)) { + return Result.succeed("设备已执行"); + } + + // 3. 构建控制消息 + JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId); + if (controlMessage == null) { + return Result.succeed("暂未开放控制权限"); + } + + // 4. 发送设备控制请求 + String url = baseUrl + "/device/instance/" + deviceId + "/property"; + Map result = requestUtils.getPostRequestResultMap(url, controlMessage.toString()); + + // 5. 处理响应结果 + return handleDeviceResponse(result, orderNo); + + } catch (Exception e) { + log.error("设置设备属性异常: deviceId={}, error={}", deviceId, e.getMessage(), e); + return Result.failed("系统异常"); + } + } + + private boolean validateParams(String control, String orderNo) { + return !StringUtils.isEmpty(control) && !StringUtils.isEmpty(orderNo); + } + + private boolean isValidOrderStatus(String orderStatus) { + return !StringUtils.isEmpty(orderStatus) && orderStatus.equals("1"); + } + + private JsonObject buildControlMessage(String control, String orderNo, String deviceId) { + if (!ControlEnum.contains(ControlEnum.valueOf(control.toUpperCase()))) { + return null; + } + + Gson gson = new Gson(); + JsonObject jsonObject = gson.fromJson(controlMessageConstant.CONTROL_MESSAGE_MAP.get(control), JsonObject.class); + JsonObject data = jsonObject.getAsJsonObject("data"); + // 设置订单信息 + data.addProperty("order_no", orderNo); + + // 获取航线信息 + Map wayResult = orderCenterService.getWaylineByOrderNo(orderNo); + String waylineFilePath = MapUtil.getStrValue(wayResult, "waylineFilePath"); + String waylineId = MapUtil.getStrValue(wayResult, "waylineId"); + log.info("waylineFilePath:{}, waylineId:{}", waylineFilePath, waylineId); + data.addProperty("wayline_link_url", waylineFilePath); + LineFile lineFile = lineFileService.findLineFileByWaylineId(waylineId); + Assert.notNull(lineFile,"航线文件签名不正确"); + data.addProperty("file_md5", lineFile.getSign()); + // 设置设备视频流地址 + try { + data.add("stream_urls", gson.fromJson(liveStreamService.generateStreamUrls(deviceId).toJSONString(), JsonElement.class)); + } catch (Exception e) { + log.error("生成设备推流/拉流地址异常: deviceId={}, error={}", deviceId, e.getMessage(), e); + data.addProperty("stream_urls", "{}"); // 或者空字符串 "" + } + + return jsonObject; + } + + private Result handleDeviceResponse(Map result, String orderNo) throws JsonProcessingException { + JSONObject object = JSONObject.parseObject(result.get("")); + if (object == null) { + return Result.failed("请求IOT平台异常"); + } + + IotRequestResult requestResult = IotRequestResult.getInstance(object); + if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) { + Result updateResult = orderCenterService.updateOrderStatusDoing(orderNo); + if (updateResult.getResp_code() != null && updateResult.getResp_code() == 0) { + return Result.succeed(updateResult.getData(), "设置成功"); + } + } + + return Result.failed("请重试"); + } + + @GetMapping("/device/wayline") + public Result getWayline(@RequestParam String no){ + return Result.succeed(orderCenterService.getWaylineByOrderNo(no)); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/IaFileController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/IaFileController.java new file mode 100644 index 00000000..1bf1806a --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/IaFileController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.IaFile; +import com.central.device.service.IIaFileService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +@Slf4j +@RestController +@RequestMapping("/file") +@Tag(name = "Media file information") +@RequiredArgsConstructor +public class IaFileController { + private final IIaFileService iaFileService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return iaFileService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + IaFile model = iaFileService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody IaFile iaFile) { + iaFileService.saveOrUpdate(iaFile); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + iaFileService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/LineFileController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/LineFileController.java new file mode 100644 index 00000000..f0b072ed --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/LineFileController.java @@ -0,0 +1,85 @@ +package com.central.device.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.device.model.LineFile; +import com.central.device.service.ILineFileService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +@Slf4j +@RestController +@RequestMapping("/wayline") +@Tag(name = "Wayline file information") +@RequiredArgsConstructor +public class LineFileController { + private final ILineFileService lineFileService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return lineFileService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findById(@PathVariable String id) { + LineFile model = lineFileService.findLineFileByWaylineId(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/sign/{id}") + public String findLineSignById(@PathVariable String id) { + LineFile model = lineFileService.findLineFileByWaylineId(id); + return model.getSign(); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody LineFile lineFile) { + lineFileService.saveOrUpdate(lineFile); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + lineFileService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/LineJobController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/LineJobController.java new file mode 100644 index 00000000..3cc5af40 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/LineJobController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.LineJob; +import com.central.device.service.ILineJobService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +@Slf4j +@RestController +@RequestMapping("/linejob") +@Tag(name = "Wayline mission information of the dock.") +@RequiredArgsConstructor +public class LineJobController { + private final ILineJobService lineJobService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return lineJobService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + LineJob model = lineJobService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody LineJob lineJob) { + lineJobService.saveOrUpdate(lineJob); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + lineJobService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/LiveStreamController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/LiveStreamController.java new file mode 100644 index 00000000..04344b2a --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/LiveStreamController.java @@ -0,0 +1,26 @@ +package com.central.device.controller; + +import com.alibaba.fastjson.JSONObject; +import com.central.common.model.Result; +import com.central.device.service.LiveStreamService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class LiveStreamController { + + @Autowired + private LiveStreamService liveStreamService; + + @GetMapping("/live/stream-urls") + public JSONObject getJsonStreamUrls(@RequestParam String deviceId) { + return liveStreamService.generateStreamUrls(deviceId); + } + + @GetMapping("/stream-urls") + public Result getStreamUrls(@RequestParam String deviceId) { + return Result.succeed(liveStreamService.generateStreamUrls(deviceId)); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/SFileController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/SFileController.java new file mode 100644 index 00000000..afd99353 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/SFileController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.SFile; +import com.central.device.service.ISFileService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +@Slf4j +@RestController +@RequestMapping("/sfile") +@Tag(name = "Logs file information") +@RequiredArgsConstructor +public class SFileController { + private final ISFileService sFileService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return sFileService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + SFile model = sFileService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody SFile sFile) { + sFileService.saveOrUpdate(sFile); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + sFileService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/SFileIndexController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/SFileIndexController.java new file mode 100644 index 00000000..c41912cb --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/SFileIndexController.java @@ -0,0 +1,76 @@ +package com.central.device.controller; + +import java.util.Map; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import lombok.extern.slf4j.Slf4j; + +import com.central.device.model.SFileIndex; +import com.central.device.service.ISFileIndexService; +import com.central.common.model.PageResult; +import com.central.common.model.Result; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +@Slf4j +@RestController +@RequestMapping("/sfile/index") +@Tag(name = "The boot index table corresponding to the logs file.") +@RequiredArgsConstructor +public class SFileIndexController { + private final ISFileIndexService sFileIndexService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return sFileIndexService.findList(params); + } + + /** + * 查询 + */ + @Operation(summary = "查询") + @GetMapping("/{id}") + public Result findUserById(@PathVariable Long id) { + SFileIndex model = sFileIndexService.getById(id); + return Result.succeed(model, "查询成功"); + } + + /** + * 新增or更新 + */ + @Operation(summary = "保存") + @PostMapping + public Result save(@RequestBody SFileIndex sFileIndex) { + sFileIndexService.saveOrUpdate(sFileIndex); + return Result.succeed("保存成功"); + } + + /** + * 删除 + */ + @Operation(summary = "删除") + @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true) + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + sFileIndexService.removeById(id); + return Result.succeed("删除成功"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/token/ApiTokenController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/token/ApiTokenController.java new file mode 100644 index 00000000..84330f00 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/token/ApiTokenController.java @@ -0,0 +1,63 @@ +package com.central.device.controller.token; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.central.common.model.Result; +import com.central.device.util.Utils; +import com.central.device.util.http.HeaderUtils; +import com.central.device.util.http.HttpRequest; +import com.central.device.util.http.Response; +import com.central.device.util.http.SimpleHttpRequest; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * token获取 + * @author lishilin + * @date 2024-12-31 + */ +@Tag(name = "token获取") +@RestController +@RequestMapping("/token") +public class ApiTokenController { + + @Value("${jetlinks.server.baseUrl}") + private String jetlinksServiceUrl;//= "http://119.45.169.13:8848/"; + + @Autowired + private HeaderUtils headerUtils; + + @Operation(summary = "客户端获取通信平台token") + @GetMapping("/query") + public Result token() throws IOException { + + String url = jetlinksServiceUrl+"/token"; + + HttpRequest request = new SimpleHttpRequest(url); + + Map param = new HashMap<>(2); + param.put("expires",7200*24); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + + + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + JSONObject jsonObject = JSON.parseObject(result.get("")); + Assert.notNull(jsonObject,"获取IOT数据异常"); + if (jsonObject.getString("message").equals("success")) { + return Result.succeed(jsonObject,"获取成功"); + } + return Result.failed("请重试"); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/feign/OrderCenterService.java b/zlt-business/device-center/src/main/java/com/central/device/feign/OrderCenterService.java new file mode 100644 index 00000000..448d65fd --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/feign/OrderCenterService.java @@ -0,0 +1,33 @@ +package com.central.device.feign; + +import com.central.common.constant.ServiceNameConstants; +import com.central.common.model.Result; +import com.central.device.feign.fallback.OrderCenterServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; + +import java.util.Map; + +/** + * user-center模块远程调用 + * + * @author lsl + * @version 1.0 + * @description user-center模块远程调用 + * @create 2025/1/13 + **/ +@FeignClient(name = ServiceNameConstants.ORDER_SERVICE, fallbackFactory = OrderCenterServiceFallbackFactory.class, dismiss404 = true) +public interface OrderCenterService { + + @PostMapping("/status") + Result updateOrderStatusDoing(@RequestBody String orderNo); + + @GetMapping("/{orderNo}/status") + String getOrderStatusByOrderNo(@PathVariable("orderNo") String orderNo); + + @GetMapping("/qrcode/wayline/{orderNo}") + Map getWaylineByOrderNo(@PathVariable("orderNo") String orderNo); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java b/zlt-business/device-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java new file mode 100644 index 00000000..80ad4c5f --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java @@ -0,0 +1,43 @@ +package com.central.device.feign.fallback; + +import com.central.common.model.Result; +import com.central.device.feign.OrderCenterService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.Map; + +/** + * 任务中心调用失败回调 + * + * @author lsl + * @version 1.0 + * @description 任务中心调用失败回调 + * @create 2025/1/17 11:33 + **/ +@Slf4j +@Component +public class OrderCenterServiceFallbackFactory implements FallbackFactory { + + + @Override + public OrderCenterService create(Throwable cause) { + return new OrderCenterService() { + @Override + public Result updateOrderStatusDoing(String orderNo) { + return null; + } + + @Override + public String getOrderStatusByOrderNo(String orderNo) { + return ""; + } + + @Override + public Map getWaylineByOrderNo(String orderNo) { + return null; + } + }; + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/listener/DeviceImportListener.java b/zlt-business/device-center/src/main/java/com/central/device/listener/DeviceImportListener.java new file mode 100644 index 00000000..74a01388 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/listener/DeviceImportListener.java @@ -0,0 +1,73 @@ +package com.central.device.listener; + +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.read.listener.ReadListener; +import com.central.device.model.AgeDevice; +import com.central.device.model.excel.AgeDeviceExcel; +import com.central.device.service.IAgeDeviceService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@Slf4j +@RequiredArgsConstructor +public class DeviceImportListener implements ReadListener { + private final IAgeDeviceService deviceService; + private final List deviceList = new ArrayList<>(); + private static final int BATCH_COUNT = 100; + + @Override + public void invoke(AgeDeviceExcel data, AnalysisContext context) { + log.info("解析到一条数据: {}", data); + + // 数据校验 + validateData(data); + + // 转换为实体 + AgeDevice device = data.toDevice(); + + // 设置默认值 + if (device.getCreateTime() == null) { + device.setCreateTime(new Date()); + } + device.setUpdateTime(new Date()); + + deviceList.add(device); + + if (deviceList.size() >= BATCH_COUNT) { + saveData(); + deviceList.clear(); + } + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + saveData(); + log.info("所有数据解析完成!"); + } + + private void validateData(AgeDeviceExcel data) { + if (StringUtils.isEmpty(data.getDeviceSn())) { + throw new IllegalArgumentException("设备序列号不能为空"); + } + if (StringUtils.isEmpty(data.getDeviceName())) { + throw new IllegalArgumentException("设备名称不能为空"); + } + // 检查设备序列号是否已存在 + AgeDevice existDevice = deviceService.getByDeviceSn(data.getDeviceSn()); + if (existDevice != null) { + throw new IllegalArgumentException("设备序列号已存在:" + data.getDeviceSn()); + } + } + + private void saveData() { + if (!deviceList.isEmpty()) { + log.info("开始保存数据,数量:{}", deviceList.size()); + deviceService.saveBatch(deviceList); + } + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java new file mode 100644 index 00000000..b85f42d8 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceFirmwareMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeDeviceFirmware; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface AgeDeviceFirmwareMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java new file mode 100644 index 00000000..2c77e129 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceHmsMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeDeviceHms; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +@Mapper +public interface AgeDeviceHmsMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java new file mode 100644 index 00000000..e6f23dc6 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceLogsMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeDeviceLogs; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +@Mapper +public interface AgeDeviceLogsMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java new file mode 100644 index 00000000..9ac2fd69 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDeviceMapper.java @@ -0,0 +1,45 @@ +package com.central.device.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.device.model.AgeDevice; +import com.central.device.model.vo.DistributionDataVO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Mapper +public interface AgeDeviceMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + @Select("SELECT COUNT(*) FROM manage_device WHERE is_del = 0") + Long getTotalDevices(); + + @Select("SELECT COUNT(*) FROM manage_device WHERE is_del = 0 AND status = 1") + Long getOnlineDevices(); + + @Select({ + "SELECT", + " device_type as type,", + " COUNT(*) as value", + "FROM manage_device", + "WHERE is_del = 0", + "GROUP BY device_type" + }) + List getDeviceDistribution(); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java new file mode 100644 index 00000000..35ffe43c --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeDevicePayloadMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeDevicePayload; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +@Mapper +public interface AgeDevicePayloadMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java new file mode 100644 index 00000000..7ee21448 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeFirmwareModelMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeFirmwareModel; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +@Mapper +public interface AgeFirmwareModelMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java new file mode 100644 index 00000000..7da5231e --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/AgeWorkspaceMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.AgeWorkspace; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +@Mapper +public interface AgeWorkspaceMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/IaFileMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/IaFileMapper.java new file mode 100644 index 00000000..2b92b51a --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/IaFileMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.IaFile; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +@Mapper +public interface IaFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/LineFileMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/LineFileMapper.java new file mode 100644 index 00000000..1818583a --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/LineFileMapper.java @@ -0,0 +1,34 @@ +package com.central.device.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.device.model.LineFile; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +@Mapper +public interface LineFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + @Select("SELECT COUNT(*) FROM wayline_file WHERE is_del = 0") + Long getTotalWaylines(); + + @Select("SELECT COUNT(*) FROM wayline_file WHERE is_del = 0 AND last_use_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)") + Long getActiveWaylines(); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/LineJobMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/LineJobMapper.java new file mode 100644 index 00000000..f3ccce11 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/LineJobMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.LineJob; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +@Mapper +public interface LineJobMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java new file mode 100644 index 00000000..06d359d9 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/SFileIndexMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.SFileIndex; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +@Mapper +public interface SFileIndexMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/mapper/SFileMapper.java b/zlt-business/device-center/src/main/java/com/central/device/mapper/SFileMapper.java new file mode 100644 index 00000000..793235b3 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/mapper/SFileMapper.java @@ -0,0 +1,27 @@ +package com.central.device.mapper; + +import com.central.device.model.SFile; +import com.central.db.mapper.SuperMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; +import java.util.Map; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +@Mapper +public interface SFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/message/ControlEnum.java b/zlt-business/device-center/src/main/java/com/central/device/message/ControlEnum.java new file mode 100644 index 00000000..5d5c0c07 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/message/ControlEnum.java @@ -0,0 +1,29 @@ +package com.central.device.message; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum ControlEnum { + RETURN_HOME("return_home"), + TAKEOFF_TO_POINT("takeoff_to_point"), + FLY_TO_POINT("fly_to_point"), + FLY_TO_POINT_STOP("fly_to_point_stop"), + FLY_TO_POINT_UPDATE("fly_to_point_stop"), + FLIGHTTASK_PAUSE("flighttask_pause"), + FLIGHTTASK_PREPARE ("flighttask_prepare"), + FLIGHTTASK_RECOVERY( "flighttask_recovery"); + + private final String name; + + // 静态方法:检查某个参数是否是枚举的一个实例 + public static boolean contains(ControlEnum value) { + for (ControlEnum v : ControlEnum.values()) { + if (v == value) { + return true; + } + } + return false; + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/message/ControlMessageConstant.java b/zlt-business/device-center/src/main/java/com/central/device/message/ControlMessageConstant.java new file mode 100644 index 00000000..15ac1d6c --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/message/ControlMessageConstant.java @@ -0,0 +1,91 @@ +package com.central.device.message; + +import lombok.Getter; + +import java.util.HashMap; +import java.util.Map; + + +@Getter +public class ControlMessageConstant { + + + public final static String TAKEOFF_TO_POINT = "{\n" + + " \"data\": {\n" + + "\t \"flight_id\": flight_id,\n" + + "\t \"max_speed\": 5,\n" + + "\t \"rc_lost_action\": 2,\n" + + "\t \"rth_altitude\": 60.0,\n" + + "\t \"rth_mode\": 1,\n" + + "\t \"security_takeoff_height\": 60.0,\n" + + "\t \"target_height\": 70.0,\n" + + "\t \"target_latitude\": 39.102603,\n" + + "\t \"target_longitude\": 117.711972,\n" + + "\t \"commander_mode_lost_action\": 0,\n" + + "\t \"commander_flight_mode\": 1,\n" + + "\t \"commander_flight_height\": 70.0,\n" + + "\t \"simulate_mission\": {\n" + + "\t },\n" + + "\t \"flight_safety_advance_check\": 0\n" + + "\t},\n" + + "\t\"method\": \"takeoff_to_point\"\n" + + "}"; + + public final static String FLY_TO_ID = "{\n" + + "\t\"data\": {\n" + + "\t\t\"fly_to_id\": \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx\",\n" + + "\t\t\"max_speed\": 12,\n" + + "\t\t\"points\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"height\": 100,\n" + + "\t\t\t\t\"latitude\": 12.23,\n" + + "\t\t\t\t\"longitude\": 12.23\n" + + "\t\t\t}\n" + + "\t\t]\n" + + "\t},\n" + + "\t\"method\": \"fly_to_point\"\n" + + "}"; + public final static String FLY_TO_ID_STOP = "{\n" + + "\t\"data\": {},\n" + + "\t\"method\": \"fly_to_point_stop\"\n" + + "}"; + public final static String FLY_TO_POINT_UPDATE = "{\n" + + "\t\"data\": {\n" + + "\t\t\"max_speed\": 12,\n" + + "\t\t\"points\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"height\": 100,\n" + + "\t\t\t\t\"latitude\": 12.23,\n" + + "\t\t\t\t\"longitude\": 12.23\n" + + "\t\t\t}\n" + + "\t\t]\n" + + "\t},\n" + + "\t\"method\": \"fly_to_point_update\"\n" + + "}"; + public final static String RETURN_HOME = "{\n" + + "\t\"data\": {},\n" + + "\t\"method\": \"return_home\"\n" + + "}"; + + public final static String FLIGHTTASK_PAUSE = "{\"data\": {}, \"method\": \"flighttask_pause\"}"; + + public final static String FLIGHTTASK_PREPARE = "{\"data\": {},\"method\": \"flighttask_prepare\"}"; + + public final static String FLIGHTTASK_RECOVERY = "{\"data\": {}, \"method\": \"flighttask_recovery\"}"; + + public Map CONTROL_MESSAGE_MAP + = new HashMap(); + + public ControlMessageConstant(){ + CONTROL_MESSAGE_MAP.put("fly_to_point_stop", FLY_TO_ID_STOP); + CONTROL_MESSAGE_MAP.put("fly_to_point", FLY_TO_ID); + CONTROL_MESSAGE_MAP.put("fly_to_point_update", FLY_TO_POINT_UPDATE); + CONTROL_MESSAGE_MAP.put("flighttask_pause", FLIGHTTASK_PAUSE); + CONTROL_MESSAGE_MAP.put("flighttask_prepare", FLIGHTTASK_PREPARE); + CONTROL_MESSAGE_MAP.put("return_home", RETURN_HOME); + CONTROL_MESSAGE_MAP.put("flighttask_recovery", FLIGHTTASK_RECOVERY); + + } + + +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/message/iot说明#上报主题.md b/zlt-business/device-center/src/main/java/com/central/device/message/iot说明#上报主题.md new file mode 100644 index 00000000..b515d017 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/message/iot说明#上报主题.md @@ -0,0 +1,747 @@ +# iot说明 + +# 上报主题说明: + +设备运行日志上报主题:/fire_alarm + +# 上报内容: + +## 状态包: + +| home_position_is_valid | Home 点有效性 | enum_int | {"0":"无效","1":"有效"} | | r | 0 | +| --- | --- | --- | --- | --- | --- | --- | +| heading | 机场朝向角 | double | {"max":"180","min":"-180","step":"","unit_name":"度 / °"} | | r | 0 | +| rtcm_info | 机场 RTK 标定源 | struct | | | r | 1 | +| »mount_point | 网络 RTK 挂载点信息 | text | | | | 0 | +| »port | 网络端口信息 | text | | | | 0 | +| »host | 网络 host 信息 | text | | | | 0 | +| »rtcm_device_type | 设备类型 | enum_int | {"1":"机场"} | | | 0 | +| »source_type | 标定类型 | enum_int | {"0":"未标定","1":"自收敛标定","2":"手动标定","3":"网络RTK标定"} | | | 0 | +| wireless_link_topo | 图传连接拓扑 | struct | | | r | 1 | +| »secret_code | 加密编码 | array | {"size": 28, "item_type": int} | | | 0 | +| »center_node | 飞行器对频信息 | struct | | | | 0 | +| »»sdr_id | 扰码信息 | int | | | | 0 | +| »»sn | 设备sn | text | | | | 0 | +| »leaf_nodes | 机场或遥控器对频信息 | array | {"size": -, "item_type": struct} | | | 0 | +| »»sdr_id | 扰码信息 | int | | | | 0 | +| »»sn | 设备sn | text | | | | 0 | +| »»control_source_index | 控制源序号 | int | {"max":"2","min":"1","step":"1","unit_name":"无 / "} | | | 0 | +| air_conditioner | 机场空调工作状态信息 | struct | | | r | 0 | +| »air_conditioner_state | 机场空调状态 | enum_int | {"0":"空闲模式(无制冷、制热、除湿等)","1":"制冷模式","2":"制热模式","3":"除湿模式","4":"制冷退出模式","5":"制热退出模式","6":"除湿退出模式","7":"制冷准备模式","8":"制热准备模式","9":"除湿准备模式"} | 机场空调工作状态信息,空调仅存在一种工作模式 | | 0 | +| »switch_time | 剩余等待可切换时间 | int | {"unit_name":"秒 / s"} | 空调状态顺序为准备模式切换到工作状模式、随后可操作后切换到退出模式、退出完成后切换到空闲模式,因此本物模型表示进行某个指令操作后还需要多久可以切换至下一状态。例如当前为空闲状态,开启制冷模式后将进入制冷准备模式,则本时间表示还需要多久可以进入制冷工作模式。以此类推 | | 0 | +| air_transfer_enable | 空中回传 | bool | {"false":"关闭","true":"开启"} | 用户在指令飞行过程中拍照的照片快速回传至云端 | rw | 1 | +| silent_mode | 机场静音模式 | enum_int | {"0":"非静音模式","1":"静音模式"} | 开启静音模式,意味着:1. 风扇转速降低、空调制冷性能下降、炎热天气下作业间隔变长。2. 蜂鸣器声音将关闭,开关舱盖时请注意周围安全。3. 机场待机状态的白色指示灯关闭,其他运行状态的指示灯正常。 | rw | 1 | +| user_experience_improvement | 用户体验改善计划 | enum_int | {"0":"初始状态","1":"拒绝加入用户体验改善计划","2":"同意加入用户体验改善计划"} | | rw | 1 | +| dongle_infos | 4G Dongle信息 | array | {"size": -, "item_type": struct} | | r | 1 | +| »imei | dongle imei | text | | Dongle 的唯一识别标志 | r | 0 | +| »dongle_type | Dongle 类型 | enum_int | {"6":"旧 Dongle","10":"支持 eSIM 的新 Dongle"} | Dongle 类型 | r | 0 | +| »eid | dongle eid | text | | eSIM 的唯一识别标志,用于公众号查询套餐、购买服务 | r | 0 | +| »esim_activate_state | eSIM 激活状态 | enum_int | {"0":"未激活","1":"已激活"} | 需要激活才能使用 | r | 0 | +| »sim_card_state | SIM 卡状态 | enum_int | {"0":"未插入","1":"已插入"} | Dongle 中实体 SIM 卡的插入状态 | r | 0 | +| »sim_slot | SIM 卡槽使能状态 | enum_int | {"0":"未知","1":"实体 SIM 卡","2":"eSIM"} | 标识 Dongle 当前正在使用的 SIM 卡槽 | r | 0 | +| »esim_infos | eSIM 信息 | array | {"size": -, "item_type": struct} | | r | 0 | +| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | eSIM 支持的运营商 | r | 0 | +| »»enabled | eSIM 使能状态 | bool | {"false":"未使用","true":"使用中"} | 同时刻只能有一个 eSIM 是使能的 | r | 0 | +| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | +| »sim_info | SIM 卡信息 | struct | | 可插入 Dongle 的实体 SIM 卡信息 | r | 0 | +| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | SIM 卡支持的运营商 | r | 0 | +| »»sim_type | SIM 卡类型 | enum_int | {"0":"未知","1":"其他普通 SIM 卡","2":"三网卡"} | 实体 SIM 卡的类型 | r | 0 | +| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | +| drone_battery_maintenance_info | 飞行器电池保养信息 | struct | | | | 0 | +| »maintenance_state | 保养状态 | enum_int | {"0":"无需保养","1":"待保养","2":"正在保养"} | | | 0 | +| »maintenance_time_left | 电池保养剩余时间 | int | {"unit_name":"小时 / h"} | 向下取整 | | 0 | +| »heat_state | 电池加热保温状态 | enum_int | {"0":"电池未开启加热或保温","1":"电池在加热中","2":"电池在保温中"} | 当飞行器舱内关机时由本物模型上报机场连接飞行器的电池加热保温信息 | | 0 | +| »batteries | 电池详细信息 | array | {"size": -, "item_type": struct} | 当飞行器舱内关机时由本物模型上报机场连接飞行器的电池信息,基本数据与飞行器物模型中电池信息基本保持一致 | | 0 | +| »»capacity_percent | 电池剩余电量 | int | {"max":100,"min":0} | 保留小数点后一位,正常范围0-100,设备端获取不到数据的异常值为 32767 | | 0 | +| »»index | 电池序号 | enum_int | {"0":"左电池","1":"右电池"} | | | 0 | +| »»voltage | 电压 | int | {"unit_name":"毫伏 / mV"} | 正常范围0-28000mV,设备端获取不到数据的异常值为32767 | | 0 | +| »»temperature | 温度 | float | {"unit_name":"摄氏度 / °C"} | 保留小数点后一位,正常范围-40-150°C,设备端获取不到数据的异常值为32767 | | 0 | +| air_conditioner | 机场空调工作状态信息 | struct | | | r | 0 | +| »air_conditioner_state | 机场空调状态 | enum_int | {"0":"空闲模式(无制冷、制热、除湿等)","1":"制冷模式","2":"制热模式","3":"除湿模式","4":"制冷退出模式","5":"制热退出模式","6":"除湿退出模式","7":"制冷准备模式","8":"制热准备模式","9":"除湿准备模式"} | 机场空调工作状态信息,空调仅存在一种工作模式 | | 0 | +| »switch_time | 剩余等待可切换时间 | int | {"unit_name":"秒 / s"} | 模式切换顺序为准备模式、工作(制冷、制热、除湿)模式、退出模式、空闲模式。本属性将上报,可以切换下一个模式指令还需要等待的时间。例如当前机场空调在进入制冷模式后,必须制冷5分钟后才可以退出制冷模式,本属性将上报还需要多久退出制冷模式,为0表示随时可退出 | | 0 | +| maintain_status | 保养信息 | struct | | | r | 0 | +| »maintain_status_array | 保养信息数组 | array | {"size": -, "item_type": struct} | | | 0 | +| »»state | 保养状态 | enum_int | {"0":"无保养","1":"有保养"} | | | 0 | +| »»last_maintain_type | 上一次保养类型 | enum_int | {"0":"无保养","17":"机场常规保养","18":"机场深度保养"} | | | 0 | +| »»last_maintain_time | 上一次保养时间 | date | {"unit_name":"秒 / s"} | | | 0 | +| »»last_maintain_work_sorties | 上一次保养时作业架次 | int | {"max":"2147483647","min":"0","step":"1"} | | | 0 | +| position_state | 搜星状态 | struct | | | r | 0 | +| »is_calibration | 是否标定 | enum_int | {"0":"未标定","1":"已标定"} | | | 0 | +| »is_fixed | 是否收敛 | enum_int | {"0":"未开始","1":"收敛中","2":"收敛成功","3":"收敛失败"} | | | 0 | +| »quality | 搜星档位 | enum_int | {"1":"1档","2":"2档","3":"3档","4":"4档","5":"5档","10":"RTK fixed"} | | | 0 | +| »gps_number | GPS 搜星数量 | int | | | | 0 | +| »rtk_number | RTK 搜星数量 | int | | | | 0 | +| emergency_stop_state | 紧急停止按钮状态 | enum_int | {"0":"关闭","1":"开启"} | | r | 0 | +| drone_charge_state | 飞行器充电状态 | struct | | 飞行器充电状态 | r | 0 | +| »capacity_percent | 电量百分比 | int | {"max":"100","min":"0"} | | | 0 | +| »state | 充电状态 | enum_int | {"0":"空闲","1":"充电中"} | | | 0 | +| backup_battery | 机场备用电池信息 | struct | | | r | 0 | +| »switch | 备用电池开关 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | +| »voltage | 备用电池电压 | int | {"desc":"备用电池关闭时电压为0","max":"30000","min":"0","step":"1","unit_name":"毫伏 / mV"} | | | 0 | +| »temperature | 备用电池温度 | float | {"step":"0.1","unit_name":"摄氏度 / °C"} | 保留小数点后一位 | | 0 | +| alarm_state | 机场声光报警状态 | enum_int | {"0":"关闭","1":"开启"} | | r | 0 | +| battery_store_mode | 电池运行模式 | enum_int | {"1":"计划模式","2":"待命模式"} | 计划模式适合规律作业场景,无任务时电池电量保持在55%~60%,电池寿命较长。待命模式适合应急作业场景,无任务时电池电量保持在90%~95%,电池寿命较短。 | r | 0 | +| activation_time | 机场激活时间(unix 时间戳) | int | {"unit_name":"秒 / s"} | | r | 0 | +| height | 椭球高度 | double | {"unit_name":"米 / m"} | | r | 0 | +| alternate_land_point | 备降点 | struct | | | r | 0 | +| »longitude | 经度 | float | {} | | | 0 | +| »latitude | 纬度 | float | {} | | | 0 | +| »safe_land_height | 安全高度(备降转移高) | float | {} | | | 0 | +| »is_configured | 是否设置备降点 | enum_int | {"0":"未设置","1":"已设置"} | | | 0 | +| »height | 椭球高度 | float | | | | 0 | +| compatible_status | 固件一致性 | enum_int | {"0":"不需要一致性升级","1":"需要一致性升级"} | 一致性升级:指飞行器某些模块的固件版本与系统匹配版本不一致,需要进行升级。常见的情况例如:飞行器与遥控器已经升级至最新版本,但替换电池时发现电池未升级,此时一致性升级将被提示。普通升级:开发者将飞行器所有模块升级至指定固件版本。 | r | 1 | +| acc_time | 机场累计运行时长 | int | {"unit_name":"秒 / s"} | | r | 1 | +| first_power_on | 首次上电时间 | int | {"unit_name":"毫秒 / ms"} | | r | 0 | +| storage | 存储容量 | struct | | | r | 0 | +| »total | 总容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | +| »used | 已使用容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | +| working_current | 工作电流 | float | {"unit_name":"毫安 / mA"} | | r | 0 | +| working_voltage | 工作电压 | int | {"unit_name":"毫伏 / mV"} | | r | 0 | +| humidity | 舱内湿度 | float | {"max":"100","min":"0","step":"0.1","unit_name":"相对湿度 / %RH"} | | r | 0 | +| temperature | 舱内温度 | float | {"unit_name":"摄氏度 / °C"} | | r | 0 | +| environment_temperature | 环境温度 | float | {"unit_name":"摄氏度 / °C"} | | r | 0 | +| wind_speed | 风速 | float | {"unit_name":"米每秒 / m/s"} | | r | 0 | +| rainfall | 降雨量 | enum_int | {"0":"无雨","1":"小雨","2":"中雨","3":"大雨"} | | r | 0 | +| live_capacity | 网关设备直播能力 | struct | | | r | 1 | +| »available_video_number | 可选择推流的码流数量 | int | | | | 0 | +| »coexist_video_number_max | 可同时推流的最大码流数量 | int | | | | 0 | +| »device_list | 可选择的视频设备源 | array | {"size": -, "item_type": struct} | 可选择的视频设备源(设备层,比如飞行器) | | 0 | +| »»sn | 飞行器等视频源设备序列号(SN) | text | | | | 0 | +| »»available_video_number | 该序列号设备可以被选择推流的码流数 | int | | | | 0 | +| »»coexist_video_number_max | 该序列号设备可以同时被推流的码流数 | int | | | | 0 | +| »»camera_list | 该序列号设备上的相机列表 | array | {"size": -, "item_type": struct} | | | 0 | +| »»»camera_index | 相机索引 | text | | 使用 *{type-subtype-gimbalindex}* 的格式 | | 0 | +| »»»available_video_number | 该相机级别的视频源可以被选择推流的码流数 | int | | | | 0 | +| »»»coexist_video_number_max | 该相机级别的视频源可以同时被推流的码流数 | int | | | | 0 | +| »»»video_list | 该相机级别的视频源可以选择的码流列表 | array | {"size": -, "item_type": struct} | | | 0 | +| »»»»video_index | 该相机级别的视频源可以选择的码流索引 | text | | | | 0 | +| »»»»video_type | 该相机级别的视频源可以选择的码流类型 | text | | | | 0 | +| »»»»switchable_video_types | 该视频流支持切换的视频镜头类型 | array | {"size": -, "item_type": text} | | | 0 | +| live_status | 网关当前整体直播状态推送 | array | {"size": -, "item_type": struct} | | r | 1 | +| »video_id | 直播码流标识符 | text | | 某路在推视频码流的标识符,格式为 *{sn}/{camera_index}/{video_index}*。其中 *{sn}* 为视频源设备序列号。*{camera_index}* 为相机索引,使用 *{type-subtype-gimbalindex}* 的格式。*{video_index}* 为该相机级别的视频源可以选择的码流索引。 | | 0 | +| »video_type | 视频类型 | text | {"length":"24"} | 表明视频镜头的类型,如normal/wide/zoom/infrared等 | | 0 | +| »video_quality | 直播码流的质量 | enum_int | {"0":"自适应","1":"流畅","2":"标清","3":"高清","4":"超清"} | | | 0 | +| »status | 直播状态 | enum_int | {"0":"未直播","1":"在直播"} | | | 0 | +| »error_status | 错误码 | int | {"length":6} | | | 0 | +| wireless_link | 图传链路 | struct | | | r | 0 | +| »dongle_number | 飞行器上 Dongle 数量 | int | | | | 0 | +| »4g_link_state | 4G 链路连接状态 | enum_int | {"0":"断开","1":"连接"} | | | 0 | +| »sdr_link_state | SDR 链路连接状态 | enum_int | {"0":"断开","1":"连接"} | | | 0 | +| »link_workmode | 机场的图传链路模式 | enum_int | {"0":"SDR 模式","1":"4G 融合模式"} | | | 0 | +| »sdr_quality | SDR 信号质量 | int | {"max":"5","min":"0","step":"1"} | | | 0 | +| »4g_quality | 总体 4G 信号质量 | int | {"max":"5","min":"0","step":"1"} | | | 0 | +| »4g_uav_quality | 天端 4G 信号质量 | int | {"max":"5","min":"0","step":"1"} | 飞行器端与 4G 服务器之间的信号质量 | | 0 | +| »4g_gnd_quality | 地端 4G 信号质量 | int | {"max":"5","min":"0","step":"1"} | 地面端(如遥控器、DJI Dock等)与 4G 服务器之间的信号质量 | | 0 | +| »sdr_freq_band | SDR 频段 | float | | | | 0 | +| »4g_freq_band | 4G 频段 | float | | | | 0 | +| media_file_detail | 媒体文件上传细节 | struct | | | r | 0 | +| »remain_upload | 待上传数量 | int | | | | 0 | +| job_number | 机场累计作业次数 | int | {"unit_name":"次 / count"} | | r | 0 | +| drone_in_dock | 飞行器是否在舱 | enum_int | {"0":"舱外","1":"舱内"} | | r | 0 | +| network_state | 网络状态 | struct | | | r | 0 | +| »type | 网络类型 | enum_int | {"1":"4G","2":"以太网"} | | | 0 | +| »quality | 网络质量 | enum_int | {"0":"无信号","1":"差","2":"较差","3":"一般","4":"较好","5":"好"} | | | 0 | +| »rate | 网络速率 | float | {"unit_name":"千字节每秒 / KB/s"} | | | 0 | +| supplement_light_state | 补光灯状态 | enum_int | {"0":"关闭","1":"打开"} | | r | 0 | +| cover_state | 舱盖状态 | enum_int | {"0":"关闭","1":"打开","2":"半开","3":"舱盖状态异常"} | | r | 0 | +| sub_device | 子设备状态 | struct | | | r | 0 | +| »device_sn | 子设备序列号(SN) | text | | | | 0 | +| »device_model_key | 子设备枚举值 | text | | 格式为 *{domain-type-subtype}* | | 0 | +| »device_online_status | 机场停机坪上的飞行器开机状态 | enum_int | {"0":"关机","1":"开机"} | | | 0 | +| »device_paired | 机场停机坪上的飞行器是否与机场对频 | enum_int | {"0":"未对频","1":"已对频"} | | | 0 | +| flighttask_step_code | 机场任务状态 | enum_int | {"0":"作业准备中","1":"飞行作业中","2":"作业后状态恢复","3":"自定义飞行区更新中","4":"地形障碍物更新中","5":"任务空闲","255":"飞行器异常","256":"未知状态"} | | r | 0 | +| mode_code | 机场状态 | enum_int | {"0":"空闲中","1":"现场调试","2":"远程调试","3":"固件升级中","4":"作业中"} | | r | 0 | +| firmware_upgrade_status | 固件升级状态 | enum_int | {"0":"未升级","1":"升级中"} | | r | 1 | +| firmware_version | 固件版本 | text | {"length":"64"} | | r | 1 | +| latitude | 纬度 | double | {"max":"90","min":"-90","step":"0.01"} | | r | 0 | +| longitude | 经度 | double | {"max":"180","min":"-180","step":"0.01"} | 网关设备的经度 | r | | + +```json +{ + "bid": "939bf66d-eb0a-4804-baad-7cbc4e175253", + "data": { + "drc_state": 0, + "flighttask_prepare_capacity": 1, + "flighttask_step_code": 1, + "media_file_detail": { "remain_upload": 0 }, + "sdr": { "down_quality": 100, "frequency_band": 2.4, "up_quality": 100 }, + "user_experience_improvement": 3, + "wireless_link": { + "4g_freq_band": 5.8, + "4g_gnd_quality": 5, + "4g_link_state": 1, + "4g_quality": 5, + "4g_uav_quality": 5, + "dongle_number": 1, + "link_workmode": 1, + "sdr_freq_band": 5.8, + "sdr_link_state": 1, + "sdr_quality": 5 + } + }, + "tid": "795e35f0-109c-4ff5-bd83-f9a7ceb8e2c6", + "timestamp": 1735466829704, + "gateway": "7CTDM6F00B744S" +} +``` + +```json +{ + "tid": "3c2afb04-e637-4b16-8cd0-c15094527398", + "bid": "933bac6c-338e-4ecd-90b9-951308c439e0", + "timestamp": 1735466829710, + "data": { + "network_state": { "type": 2, "quality": 0, "rate": 32 }, + "drone_charge_state": { "state": 0, "capacity_percent": 72 }, + "drone_in_dock": 0, + "rainfall": 0, + "wind_speed": 0, + "environment_temperature": 7.1, + "temperature": 6.6, + "humidity": 45, + "heading": -72.980140686035156, + "home_position_is_valid": 1, + "latitude": 39.10260381347603, + "longitude": 117.71197297315571, + "height": 5.8588995933532715, + "alternate_land_point": { + "latitude": 39.102598739909752, + "longitude": 117.71198964942272, + "height": 0, + "safe_land_height": 30, + "is_configured": 1 + }, + "first_power_on": 1631945855969, + "position_state": { + "is_calibration": 1, + "is_fixed": 2, + "quality": 5, + "gps_number": 7, + "rtk_number": 36 + }, + "storage": { "total": 79981124, "used": 69124 }, + "mode_code": 4, + "cover_state": 0, + "silent_mode": 1, + "supplement_light_state": 0, + "emergency_stop_state": 0, + "air_conditioner": { "air_conditioner_state": 0, "switch_time": 0 }, + "battery_store_mode": 2, + "alarm_state": 0, + "putter_state": 0, + "sub_device": { + "device_sn": "1581F6QAD249M00GCRF5", + "device_online_status": 1, + "device_paired": 1 + } + }, + "gateway": "7CTDM6F00B744S" +} +``` + +```json +{ + "tid": "f219d8d5-2c57-4a0e-b9a9-d72c77ea7dbe", + "bid": "f188e509-41d3-4e70-bb63-938b15193387", + "timestamp": 1735466829726, + "data": { + "job_number": 48, + "acc_time": 618911, + "activation_time": 1734482524, + "maintain_status": { + "maintain_status_array": [ + { + "state": 0, + "last_maintain_type": 17, + "last_maintain_time": 0, + "last_maintain_work_sorties": 0 + }, + { + "state": 0, + "last_maintain_type": 18, + "last_maintain_time": 0, + "last_maintain_work_sorties": 0 + } + ] + }, + "electric_supply_voltage": 32767, + "working_voltage": 27742, + "working_current": 0, + "backup_battery": { "voltage": 13601, "temperature": 12.4, "switch": 1 }, + "drone_battery_maintenance_info": { + "maintenance_state": 0, + "maintenance_time_left": 0, + "heat_state": 0, + "batteries": [ + { + "index": 0, + "capacity_percent": 72, + "voltage": 15366, + "temperature": 24.9 + } + ] + } + }, + "gateway": "7CTDM6F00B744S" +} +``` + +```json +{ + "bid": "883e903f-1ff7-4015-8c5c-a0c0c267aff5", + "data": { + "rtcm_info": { + "host": "120.253.226.97", + "mount_point": "RTCM33_GRCEJ", + "port": "8002", + "rtcm_device_type": 1, + "source_type": 3 + } + }, + "need_reply": 1, + "tid": "3116ca3e-3335-4467-8b8e-c2b028fce07f", + "timestamp": 1735466831441, + "gateway": "7CTDM6F00B744S" +} +``` + +飞机: + +| best_link_gateway | 飞行器图传连接质量最好的网关SN | text | | 蛙跳任务场景下,当飞行器对频了两个机场后,推送连接最好的机场SN | r | 1 | +| --- | --- | --- | --- | --- | --- | --- | +| wireless_link_topo | 图传连接拓扑 | struct | | | r | 1 | +| »secret_code | 加密编码 | array | {"size": 28, "item_type": int} | | | 0 | +| »center_node | 飞行器对频信息 | struct | | | | 0 | +| »»sdr_id | 扰码信息 | int | | | | 0 | +| »»sn | 设备sn | text | | | | 0 | +| »leaf_nodes | 当前连接的机场或遥控器对频信息 | array | {"size": -, "item_type": struct} | | | 0 | +| »»sdr_id | 扰码信息 | int | | | | 0 | +| »»sn | 设备sn | text | | | | 0 | +| »»control_source_index | 控制源序号 | int | {"max":"2","min":"1","step":"1","unit_name":"无 / "} | | | 0 | +| cameras | 飞行器相机信息 | array | {"size": -, "item_type": struct} | | r | 0 | +| »remain_photo_num | 剩余拍照张数 | int | | 剩余拍照张数 | | 0 | +| »remain_record_duration | 剩余录像时间 | int | {"unit_name":"秒 / s"} | 剩余录像时间 | | 0 | +| »record_time | 视频录制时长 | int | {"unit_name":"秒 / s"} | 视频录制时长 | | 0 | +| »payload_index | 负载编号 | text | | 负载编号,相机枚举值。非标准的 device_mode_key,格式为 {type-subtype-gimbalindex},可以参考[**产品支持open in new window**](https://developer.dji.com/doc/cloud-api-tutorial/cn/overview/product-support.html) | | 0 | +| »camera_mode | 相机模式 | enum_int | {"0":"拍照","1":"录像","2":"智能低光","3":"全景拍照"} | 相机模式 | | 0 | +| »photo_state | 拍照状态 | enum_int | {"0":"空闲","1":"拍照中"} | 拍照状态 | | 0 | +| »screen_split_enable | 分屏是否使能 | bool | {"0":"分屏使能关闭","1":"分屏使能开启"} | | | 0 | +| »recording_state | 录像状态 | enum_int | {"0":"空闲","1":"录像中"} | 录像状态 | | 0 | +| »zoom_factor | 变焦倍数 | float | | | | 0 | +| »ir_zoom_factor | 红外变焦倍数 | float | | 红外变焦倍数 | | 0 | +| »liveview_world_region | 视场角(FOV)在 liveview 中的区域 | struct | | 变焦相机的视场角相对于广角相机或者红外相机的视场角,在 liveview 中会有所不同。坐标原点为镜头左上角。 | | 0 | +| »»left | 左上角的 x 轴起始点 | float | | 左上角的 x 轴起始点 | r | 0 | +| »»top | 左上角的 y 轴起始点 | float | | 左上角的 y 轴起始点 | r | 0 | +| »»right | 右下角的 x 轴起始点 | float | | 右下角的 x 轴起始点 | r | 0 | +| »»bottom | 右下角的 y 轴起始点 | float | | 右下角的 y 轴起始点 | r | 0 | +| »photo_storage_settings | 照片存储设置集合 | array | {"size": -, "item_type": enum_string} | 取值范围{current, vision, ir} | | 0 | +| »video_storage_settings | 视频存储设置集合 | array | {"size": -, "item_type": enum_string} | 取值范围{current, vision, ir} | | 0 | +| »wide_exposure_mode | 广角镜头曝光模式 | enum_int | {"1":"自动","2":"快门优先曝光","3":"光圈优先曝光","4":"手动曝光"} | 当前配置的广角镜头曝光模式 | | 0 | +| »wide_iso | 广角镜头感光度 | enum_int | {"0":"Auto","1":"Auto(High Sense)","2":"50","3":"100","4":"200","5":"400","6":"800","7":"1600","8":"3200","9":"6400","10":"12800","11":"25600","255":"FIXED"} | 当前配置的广角镜头感光度 | | 0 | +| »wide_shutter_speed | 广角镜头快门速度 | enum_int | {"0":"1/8000 s","1":"1/6400 s","2":"1/6000 s","3":"1/5000 s","4":"1/4000 s","5":"1/3200 s","6":"1/3000 s","7":"1/2500 s","8":"1/2000 s","9":"1/1600 s","10":"1/1500 s","11":"1/1250 s","12":"1/1000 s","13":"1/800 s","14":"1/725 s","15":"1/640 s","16":"1/500 s","17":"1/400 s","18":"1/350 s","19":"1/320 s","20":"1/250 s","21":"1/240 s","22":"1/200 s","23":"1/180 s","24":"1/160 s","25":"1/125 s","26":"1/120 s","27":"1/100 s","28":"1/90 s","29":"1/80 s","30":"1/60 s","31":"1/50 s","32":"1/40 s","33":"1/30 s","34":"1/25 s","35":"1/20 s","36":"1/15 s","37":"1/12.5 s","38":"1/10 s","39":"1/8 s","40":"1/6.25 s","41":"1/5 s","42":"1/4 s","43":"1/3 s","44":"1/2.5 s","45":"1/2 s","46":"1/1.67 s","47":"1/1.25 s","48":"1.0 s","49":"1.3 s","50":"1.6 s","51":"2.0 s","52":"2.5 s","53":"3.0 s","54":"3.2 s","55":"4.0 s","56":"5.0 s","57":"6.0 s","58":"7.0 s","59":"8.0 s","65534":"Auto"} | 当前配置的广角镜头快门速度 | | 0 | +| »wide_exposure_value | 广角镜头曝光值 | enum_int | {"1":"-5.0EV","2":"-4.7EV","3":"-4.3EV","4":"-4.0EV","5":"-3.7EV","6":"-3.3EV","7":"-3.0EV","8":"-2.7EV","9":"-2.3EV","10":"-2.0EV","11":"-1.7EV","12":"-1.3EV","13":"-1.0EV","14":"-0.7EV","15":"-0.3EV","16":"0EV","17":"0.3EV","18":"0.7EV","19":"1.0EV","20":"1.3EV","21":"1.7EV","22":"2.0EV","23":"2.3EV","24":"2.7EV","25":"3.0EV","26":"3.3EV","27":"3.7EV","28":"4.0EV","29":"4.3EV","30":"4.7EV","31":"5.0EV","255":"FIXED"} | 当前配置的广角镜头曝光值 | | 0 | +| »zoom_exposure_mode | 变焦镜头曝光模式 | enum_int | {"1":"自动","2":"快门优先曝光","3":"光圈优先曝光","4":"手动曝光"} | 当前配置的变焦镜头曝光模式 | | 0 | +| »zoom_iso | 变焦镜头感光度 | enum_int | {"0":"Auto","1":"Auto(High Sense)","2":"50","3":"100","4":"200","5":"400","6":"800","7":"1600","8":"3200","9":"6400","10":"12800","11":"25600","255":"FIXED"} | 当前配置的变焦镜头感光度 | | 0 | +| »zoom_shutter_speed | 变焦镜头快门速度 | enum_int | {"0":"1/8000 s","1":"1/6400 s","2":"1/6000 s","3":"1/5000 s","4":"1/4000 s","5":"1/3200 s","6":"1/3000 s","7":"1/2500 s","8":"1/2000 s","9":"1/1600 s","10":"1/1500 s","11":"1/1250 s","12":"1/1000 s","13":"1/800 s","14":"1/725 s","15":"1/640 s","16":"1/500 s","17":"1/400 s","18":"1/350 s","19":"1/320 s","20":"1/250 s","21":"1/240 s","22":"1/200 s","23":"1/180 s","24":"1/160 s","25":"1/125 s","26":"1/120 s","27":"1/100 s","28":"1/90 s","29":"1/80 s","30":"1/60 s","31":"1/50 s","32":"1/40 s","33":"1/30 s","34":"1/25 s","35":"1/20 s","36":"1/15 s","37":"1/12.5 s","38":"1/10 s","39":"1/8 s","40":"1/6.25 s","41":"1/5 s","42":"1/4 s","43":"1/3 s","44":"1/2.5 s","45":"1/2 s","46":"1/1.67 s","47":"1/1.25 s","48":"1.0 s","49":"1.3 s","50":"1.6 s","51":"2.0 s","52":"2.5 s","53":"3.0 s","54":"3.2 s","55":"4.0 s","56":"5.0 s","57":"6.0 s","58":"7.0 s","59":"8.0 s","65534":"Auto"} | 当前配置的变焦镜头快门速度 | | 0 | +| »zoom_exposure_value | 变焦镜头曝光值 | enum_int | {"1":"-5.0EV","2":"-4.7EV","3":"-4.3EV","4":"-4.0EV","5":"-3.7EV","6":"-3.3EV","7":"-3.0EV","8":"-2.7EV","9":"-2.3EV","10":"-2.0EV","11":"-1.7EV","12":"-1.3EV","13":"-1.0EV","14":"-0.7EV","15":"-0.3EV","16":"0EV","17":"0.3EV","18":"0.7EV","19":"1.0EV","20":"1.3EV","21":"1.7EV","22":"2.0EV","23":"2.3EV","24":"2.7EV","25":"3.0EV","26":"3.3EV","27":"3.7EV","28":"4.0EV","29":"4.3EV","30":"4.7EV","31":"5.0EV","255":"FIXED"} | 当前配置的变焦镜头曝光值 | | 0 | +| »zoom_focus_mode | 变焦镜头对焦模式 | enum_int | {"0":"MF","1":"AFS","2":"AFC"} | | | 0 | +| »zoom_focus_value | 变焦镜头对焦值 | int | | | | 0 | +| »zoom_max_focus_value | 变焦镜头最大对焦值 | int | | | | 0 | +| »zoom_min_focus_value | 变焦镜头最小对焦值 | int | | | | 0 | +| »zoom_calibrate_farthest_focus_value | 变焦镜头标定的最远对焦值 | int | | 最清晰的最远位置对焦值 | | 0 | +| »zoom_calibrate_nearest_focus_value | 变焦镜头标定的最近对焦值 | int | | 最清晰的最近位置对焦值 | | 0 | +| »zoom_focus_state | 变焦镜头对焦状态 | enum_int | {"0":"空闲","1":"对焦中","2":"对焦成功","3":"对焦失败"} | | | 0 | +| »ir_metering_mode | 红外测温模式 | enum_int | {"0":"关闭测温","1":"点测温","2":"区域测温"} | | | 0 | +| »ir_metering_point | 红外测温点 | struct | | 红外测温点相关信息 | | 0 | +| »»x | 测温点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | +| »»y | 测温点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | +| »»temperature | 测温点的温度 | double | | | r | 0 | +| »ir_metering_area | 红外测温区域 | struct | | 红外测温区域相关信息 | | 0 | +| »»x | 测温区域左上角点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | +| »»y | 测温区域左上角点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | +| »»width | 测温区域宽度 | double | {"max":1,"min":0} | 测温区域宽度 | r | 0 | +| »»height | 测温区域高度 | double | {"max":1,"min":0} | 测温区域高度 | r | 0 | +| »»aver_temperature | 测温区域平均温度 | double | | 测温区域平均温度 | r | 0 | +| »»min_temperature_point | 测温区域最低温度点 | struct | | 测温区域最低温度点相关信息 | r | 0 | +| »»»x | 最低温度点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | +| »»»y | 最低温度点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | +| »»»temperature | 最低温度点的温度 | double | | 最低温度点的温度 | r | 0 | +| »»max_temperature_point | 测温区域最高温度点 | struct | | 测温区域最高温度点相关信息 | r | 0 | +| »»»x | 最高温度点坐标 x | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,水平方向为 x | r | 0 | +| »»»y | 最高温度点坐标 y | double | {"max":1,"min":0} | 以镜头的左上角为坐标中心点,竖直方向为 y | r | 0 | +| »»»temperature | 最高温度点的温度 | double | | 最高温度点的温度 | r | 0 | +| flysafe_database_version | 飞行安全数据库版本 | text | {"length":"64"} | | r | 1 | +| offline_map_enable | 离线地图开关 | bool | {"0":"关闭","1":"开启"} | 当离线地图关闭后,离线地图同步不再进行自动同步 | r | 1 | +| dongle_infos | 4G Dongle信息 | array | {"size": -, "item_type": struct} | | r | 1 | +| »imei | dongle imei | text | | Dongle 的唯一识别标志 | r | 0 | +| »dongle_type | Dongle 类型 | enum_int | {"6":"旧 Dongle","10":"支持 eSIM 的新 Dongle"} | Dongle 类型 | r | 0 | +| »eid | dongle eid | text | | eSIM 的唯一识别标志,用于公众号查询套餐、购买服务 | r | 0 | +| »esim_activate_state | eSIM 激活状态 | enum_int | {"0":"未激活","1":"已激活"} | 需要激活才能使用 | r | 0 | +| »sim_card_state | SIM 卡状态 | enum_int | {"0":"未插入","1":"已插入"} | Dongle 中实体 SIM 卡的插入状态 | r | 0 | +| »sim_slot | SIM 卡槽使能状态 | enum_int | {"0":"未知","1":"实体 SIM 卡","2":"eSIM"} | 标识 Dongle 当前正在使用的 SIM 卡槽 | r | 0 | +| »esim_infos | eSIM 信息 | array | {"size": -, "item_type": struct} | | r | 0 | +| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | eSIM 支持的运营商 | r | 0 | +| »»enabled | eSIM 使能状态 | bool | {"false":"未使用","true":"使用中"} | 同时刻只能有一个 eSIM 是使能的 | r | 0 | +| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | +| »sim_info | SIM 卡信息 | struct | | 可插入 Dongle 的实体 SIM 卡信息 | r | 0 | +| »»telecom_operator | 支持的运营商 | enum_int | {"0":"未知","1":"移动","2":"联通","3":"电信"} | SIM 卡支持的运营商 | r | 0 | +| »»sim_type | SIM 卡类型 | enum_int | {"0":"未知","1":"其他普通 SIM 卡","2":"三网卡"} | 实体 SIM 卡的类型 | r | 0 | +| »»iccid | sim iccid | text | | SIM 卡的唯一识别标志,可以用于实体 SIM 卡的套餐购买 | r | 0 | +| current_rth_mode | 返航高度模式当前值 | enum_int | {"0":"智能高度","1":"设定高度"} | 大疆机场当前实际使用的返航高度模式 | r | 1 | +| rth_mode | 返航高度模式设置值 | enum_int | {"0":"智能高度","1":"设定高度"} | 智能返航模式下,飞行器将自动规划最佳返航高度。大疆机场当前不支持设置返航高度模式,只能选择'设定高度'模式。当环境,光线不满足视觉系统要求时(譬如傍晚阳光直射、夜间弱光无光),飞行器将使用您设定的返航高度进行直线返航 | r | 1 | +| obstacle_avoidance | 飞行器避障状态 | struct | | | rw | 0 | +| »horizon | 水平避障状态 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | +| »upside | 上视避障状态 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | +| »downside | 下视避障状态 | enum_int | {"0":"关闭","1":"开启"} | | | 0 | +| is_near_area_limit | 是否接近限飞区 | enum_int | {"0":"未达到限飞区","1":"接近限飞区"} | | r | 0 | +| is_near_height_limit | 是否接近设定的限制高度 | enum_int | {"0":"未达到设定的限制高度","1":"接近设定的限制高度"} | | r | 0 | +| height_limit | 飞行器限高 | int | {"max":"1500","min":"20","step":"1","unit_name":"米 / m"} | | rw | 0 | +| night_lights_state | 飞行器夜航灯状态 | enum_int | {"0":"关闭","1":"打开"} | | rw | 0 | +| activation_time | 飞行器激活时间(unix 时间戳) | int | {"unit_name":"秒 / s"} | | r | 0 | +| maintain_status | 保养信息 | struct | | | r | 0 | +| »maintain_status_array | 保养信息数组 | array | {"size": -, "item_type": struct} | | | 0 | +| »»state | 保养状态 | enum_int | {"0":"无保养","1":"有保养"} | | | 0 | +| »»last_maintain_type | 上一次保养类型 | enum_int | {"1":"飞行器基础保养","2":"飞行器常规保养","3":"飞行器深度保养"} | | | 0 | +| »»last_maintain_time | 上一次保养时间 | date | {"unit_name":"秒 / s"} | | | 0 | +| »»last_maintain_flight_time | 上一次保养时飞行航时 | int | {"unit_name":"小时 / h"} | | | 0 | +| »»last_maintain_flight_sorties | 上一次保养时飞行架次 | int | {"max":"2147483647","min":"0","step":"1"} | | | 0 | +| total_flight_sorties | 飞行器累计飞行总架次 | int | {"max":"2147483647","min":"0","step":"1"} | | r | 0 | +| type_subtype_gimbalindex | 负载编号 | struct | | 与字段 payload_index 保持一致 | r | 0 | +| »gimbal_pitch | 云台俯仰轴角度 | double | {"max":"180","min":"-180","step":0.1,"unit_name":"度 / °"} | | | 0 | +| »gimbal_roll | 云台横滚轴角度 | double | {"max":"180","min":"-180","step":0.1,"unit_name":"度 / °"} | | | 0 | +| »gimbal_yaw | 云台偏航轴角度 | double | {"max":"180","min":"-180","step":0.1,"unit_name":"度 / °"} | | | 0 | +| »payload_index | 负载索引,格式为 *{type-subtype-gimbalindex}* | text | | | | 0 | +| »zoom_factor | 变焦倍数 | double | | | | 0 | +| track_id | 航迹 ID | text | {"length":"64"} | | r | 0 | +| position_state | 搜星状态 | struct | | | r | 0 | +| »is_fixed | 是否收敛 | enum_int | {"0":"未开始","1":"收敛中","2":"收敛成功","3":"收敛失败"} | | | 0 | +| »quality | 搜星档位 | enum_int | {"1":"1档","2":"2档","3":"3档","4":"4档","5":"5档","10":"RTK fixed"} | | | 0 | +| »gps_number | GPS 搜星数量 | int | | | | 0 | +| »rtk_number | RTK 搜星数量 | int | | | | 0 | +| storage | 存储容量 | struct | | kb | r | 0 | +| »total | 总容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | +| »used | 已使用容量 | int | {"unit_name":"千字节 / KB"} | | | 0 | +| battery | 飞行器电池信息 | struct | | | r | 0 | +| »capacity_percent | 电池的总剩余电量 | int | {"max":100,"min":0} | | | 0 | +| »remain_flight_time | 剩余飞行时间 | int | {"unit_name":"秒 / s"} | | | 0 | +| »return_home_power | 返航所需电量百分比 | int | {"max":100,"min":0} | | | 0 | +| »landing_power | 强制降落电量百分比 | int | {"max":100,"min":0} | | | 0 | +| »batteries | 电池详细信息 | array | {"size": -, "item_type": struct} | | | 0 | +| »»capacity_percent | 电池剩余电量 | int | {"max":100,"min":0} | | | 0 | +| »»index | 电池序号 | int | {"min":"0"} | | | 0 | +| »»sn | 电池序列号(SN) | text | | | | 0 | +| »»type | 电池类型 | enum_int | {} | | | 0 | +| »»sub_type | 电池子类型 | enum_int | {} | | | 0 | +| »»firmware_version | 固件版本 | text | | | | 0 | +| »»loop_times | 电池循环次数 | int | | | | 0 | +| »»voltage | 电压 | int | {"unit_name":"毫伏 / mV"} | | | 0 | +| »»temperature | 温度 | float | {"unit_name":"摄氏度 / °C"} | 保留小数点后一位 | | 0 | +| »»high_voltage_storage_days | 高电压存储天数 | int | {"unit_name":"日 / day"} | | | 0 | +| total_flight_distance | 飞行器累计飞行总里程 | float | {"unit_name":"米 / m"} | | r | 0 | +| total_flight_time | 飞行器累计飞行航时 | int | {"unit_name":"秒 / s"} | | r | 0 | +| serious_low_battery_warning_threshold | 严重低电量告警 | int | | 用户设置的电池严重低电量告警百分比 | r | 1 | +| low_battery_warning_threshold | 低电量告警 | int | | 用户设置的电池低电量告警百分比 | r | 1 | +| control_source | 当前控制源 | text | | 可以为设备,也可以为某个浏览器。设备使用 A/B 表示 A 控,B 控,浏览器以自生成的 uuid 作为标识符 | r | 1 | +| wind_direction | 当前风向 | enum_int | {"1":"正北","2":"东北","3":"东","4":"东南","5":"南","6":"西南","7":"西","8":"西北"} | | r | 0 | +| wind_speed | 风速 | float | | 风速估计,该风速是通过飞行器姿态推测出的,有一定的误差,仅供参考,不能作为气象数据使用 | r | 0 | +| home_distance | 距离 Home 点的距离 | float | | | r | 0 | +| home_latitude | Home 点纬度 | float | | | r | 1 | +| home_longitude | Home 点经度 | float | | | r | 1 | +| attitude_head | 偏航轴角度 | int | | 偏航轴角度与真北角(经线)的角度,0到6点钟方向为正值,6到12点钟方向为负值 | r | 0 | +| attitude_roll | 横滚轴角度 | float | | | r | 0 | +| attitude_pitch | 俯仰轴角度 | float | | | r | 0 | +| elevation | 相对起飞点高度 | float | | | r | 0 | +| height | 绝对高度 | float | | 相对地球椭球面高度, 计算:相对起飞点的高度 + 起飞点的椭球高 | r | 0 | +| latitude | 当前位置纬度 | float | {"max":"3.4028235E38","min":"-1.4E-45","step":"0.1"} | | r | 0 | +| longitude | 当前位置经度 | float | {"max":"3.4028235E38","min":"-1.4E-45","step":"0.1"} | | r | 0 | +| vertical_speed | 垂直速度 | float | {"unit_name":"米每秒 / m/s"} | | r | 0 | +| horizontal_speed | 水平速度 | float | | | r | 0 | +| firmware_upgrade_status | 固件升级状态 | enum_int | {"0":"未升级","1":"升级中"} | | r | 1 | +| compatible_status | 固件一致性 | enum_int | {"0":"不需要一致性升级","1":"需要一致性升级"} | 一致性升级:指飞行器某些模块的固件版本与系统匹配版本不一致,需要进行升级。常见的情况例如:飞行器与遥控器已经升级至最新版本,但替换电池时发现电池未升级,此时一致性升级将被提示。普通升级:开发者将飞行器所有模块升级至指定固件版本。 | r | 1 | +| firmware_version | 固件版本 | text | {"length":"64"} | | r | 1 | +| gear | 档位 | enum_int | {"0":"A","1":"P","2":"NAV","3":"FPV","4":"FARM","5":"S","6":"F","7":"M","8":"G","9":"T"} | | r | 0 | +| mode_code_reason | 飞行器进入当前状态的原因 | enum_int | {"0":"无意义","1":"电池电量不足(返航、降落)","2":"电池电压不足(返航、降落)","3":"电压严重过低(返航、降落)","4":"遥控器按键请求(起飞、返航、降落)","5":"App 请求(起飞、返航、降落)","6":"遥控信号丢失(返航、降落、悬停)","7":"导航、SDK 等外部设备触发(起飞、返航、降落)","8":"进入机场限飞区(降落)","9":"虽然触发了返航但是因为距离 Home 点距离太近(降落)","10":"虽然触发了返航但是因为距离 Home 点距离太远(降落)","11":"执行航点任务时请求(起飞)","12":"返航阶段到达 Home 点上方后请求(降落)","13":"飞行器高度下降,距地面 0.7m(二段降落限低)时,继续下降导致(降落)","14":"App、SDK 等设备强制突破限低保护进行(降落)","15":"因为周围有航班经过而请求(返航、降落)","16":"因为高度控制失败请求(返航、降落)","17":"智能低电量返航后进入(降落)","18":"AP控制飞行模式(手动飞行)","19":"硬件异常(返航、降落)","20":"防触地保护结束(降落)","21":"返航取消 (悬停)","22":"返航时遇到障碍物(降落)","23":"机场场景下大风触发(返航)"} | | r | 1 | +| commander_flight_height | 指点飞行高度 | float | {"max":3000,"min":2,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT | rw | 1 | +| commander_flight_mode | 指点飞行模式设置值 | enum_int | {"0":"智能高度飞行","1":"设定高度飞行"} | 指点飞行模式设置值 | rw | 1 | +| commander_mode_lost_action | 指点飞行失控动作 | enum_int | {"0":"继续执行指点飞行任务","1":"退出指点飞行任务,执行普通失控行为"} | 执行指点飞行时失控了,选择继续执行完,还是执行普通失控行为 | rw | 1 | +| camera_watermark_settings | 相机水印设置 | struct | | 用户对相机拍摄的照片和录像文件进行水印配置, 目前暂不支持直播画面水印 | rw | 1 | +| »global_enable | 水印显示全局开关 | enum_int | {"0":"关闭","1":"开启"} | 需要开启全局开关才能显示水印 | rw | 1 | +| »drone_type_enable | 机型显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | +| »drone_sn_enable | 飞行器序列号显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | +| »datetime_enable | 日期时间显示开关 | enum_int | {"0":"关闭","1":"开启"} | 时区默认为当地时区 | rw | 1 | +| »gps_enable | 经纬度&海拔高显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | +| »user_custom_string_enable | 自定义文案显示开关 | enum_int | {"0":"关闭","1":"开启"} | | rw | 1 | +| »user_custom_string | 自定义文案内容 | text | | 最多可显示 250 字节 | rw | 1 | +| »layout | 水印在画面中位置 | enum_int | {"0":"左上","1":"左下","2":"右上","3":"右下"} | | rw | 1 | +| mode_code | 飞行器状态 | enum_int | {"0":"待机","1":"起飞准备","2":"起飞准备完毕","3":"手动飞行","4":"自动起飞","5":"航线飞行","6":"全景拍照","7":"智能跟随","8":"ADS-B 躲避","9":"自动返航","10":"自动降落","11":"强制降落","12":"三桨叶降落","13":"升级中","14":"未连接","15":"APAS","16":"虚拟摇杆状态","17":"指令飞行","18":"空中 RTK 收敛模式","19":"机场选址中"} | 机场选址指飞行器在空中悬停,为机场选址以及检查 RTK 信号质量 | r | 0 | + +```json +{ + "bid": "f7f2dd20-a08a-4865-9211-f0ced31a798c", + "data": { + "80-0-0": { + "gimbal_pitch": 0, + "gimbal_roll": 0, + "gimbal_yaw": -72.9804724552571, + "payload_index": "80-0-0", + "zoom_factor": 0.56782334384858046 + }, + "activation_time": 1734637617, + "attitude_head": -72.9, + "attitude_pitch": -0.4, + "attitude_roll": -3, + "battery": { + "batteries": [ + { + "capacity_percent": 78, + "firmware_version": "26.03.00.48", + "high_voltage_storage_days": 8, + "index": 0, + "loop_times": 6, + "sn": "6Q7PM4ADA100QQ", + "sub_type": 0, + "temperature": 23.9, + "type": 0, + "voltage": 15544 + } + ], + "capacity_percent": 78, + "landing_power": 8, + "remain_flight_time": 1553, + "return_home_power": 26 + }, + "best_link_gateway": "7CTDM6F00B744S", + "cameras": [ + { + "camera_mode": 1, + "liveview_world_region": { + "bottom": 1, + "left": 1, + "right": 1, + "top": 1 + }, + "payload_index": "80-0-0", + "photo_state": 0, + "record_time": 0, + "recording_state": 0, + "remain_photo_num": 0, + "remain_record_duration": 29207, + "wide_calibrate_farthest_focus_value": 35, + "wide_calibrate_nearest_focus_value": 84, + "wide_exposure_mode": 1, + "wide_exposure_value": 16, + "wide_focus_mode": 2, + "wide_focus_state": 1, + "wide_focus_value": 26, + "wide_iso": 9, + "wide_max_focus_value": 84, + "wide_min_focus_value": 35, + "wide_shutter_speed": 33, + "zoom_calibrate_farthest_focus_value": 35, + "zoom_calibrate_nearest_focus_value": 84, + "zoom_exposure_mode": 1, + "zoom_exposure_value": 16, + "zoom_factor": 1, + "zoom_focus_mode": 2, + "zoom_focus_state": 1, + "zoom_focus_value": 26, + "zoom_iso": 9, + "zoom_max_focus_value": 84, + "zoom_min_focus_value": 35, + "zoom_shutter_speed": 33 + } + ], + "country": "CN", + "distance_limit_status": { + "distance_limit": 5000, + "is_near_distance_limit": 0, + "state": 0 + }, + "elevation": 64, + "gear": 1, + "height": 69.8617935180664, + "height_limit": 220, + "home_distance": 0.11966302990913391, + "horizontal_speed": 0, + "is_near_area_limit": 1, + "is_near_height_limit": 0, + "latitude": 39.102602928799222, + "longitude": 117.71197176283638, + "maintain_status": { + "maintain_status_array": [ + { + "last_maintain_flight_sorties": 0, + "last_maintain_flight_time": 0, + "last_maintain_time": 0, + "last_maintain_type": 1, + "state": 0 + }, + { + "last_maintain_flight_sorties": 0, + "last_maintain_flight_time": 0, + "last_maintain_time": 0, + "last_maintain_type": 2, + "state": 0 + }, + { + "last_maintain_flight_sorties": 0, + "last_maintain_flight_time": 0, + "last_maintain_time": 0, + "last_maintain_type": 3, + "state": 0 + } + ] + }, + "mode_code": 9, + "night_lights_state": 0, + "obstacle_avoidance": { "downside": 0, "horizon": 0, "upside": 0 }, + "position_state": { + "gps_number": 32, + "is_fixed": 2, + "quality": 5, + "rtk_number": 33 + }, + "rc_lost_action": 2, + "rid_state": true, + "rth_altitude": 60, + "storage": { "total": 243702000, "used": 4000 }, + "total_flight_distance": 174010.89760393579, + "total_flight_sorties": 57, + "total_flight_time": 28866.739354778081, + "track_id": "586f7b33-4727-4026-a203-cf35a68626e5", + "vertical_speed": 0, + "wind_direction": 6, + "wind_speed": 35 + }, + "tid": "795fbf18-8bc1-43f7-bd10-895973319cb5", + "timestamp": 1735473362062, + "gateway": "7CTDM6F00B744S" +} +``` + +```json +{ + "bid": "78f3725d-34c3-4498-b0d5-98d50dc0310d", + "data": { "mode_code_reason": 12 }, + "need_reply": 1, + "tid": "88933f47-e55e-4e9e-a100-7a073cc09086", + "timestamp": 1735473362258, + "gateway": "7CTDM6F00B744S" +} +``` + +## 指令 + +### 起飞指令: + +| target_latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 | +| --- | --- | --- | --- | --- | +| target_longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 | +| target_height | 目标点高度 | float | {"max":1500,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型,飞行器到点后默认行为:悬停 | +| security_takeoff_height | 安全起飞高度 | float | {"max":1500,"min":20,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度(ALT),飞行器先升到特定的高度,然后再飞向目标点。 | +| rth_mode | 【必填】返航模式设置值 | enum_int | {"0":"智能高度","1":"设定高度"} | 智能返航模式下,飞行器将自动规划最佳返航高度。大疆机场当前不支持设置返航高度模式,只能选择'设定高度'模式。当环境,光线不满足视觉系统要求时(譬如傍晚阳光直射、夜间弱光无光),飞行器将使用您设定的返航高度进行直线返航 | +| rth_altitude | 返航高度 | int | {"max":1500,"min":2,"step":1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT | +| rc_lost_action | 遥控器失控动作 | enum_int | {"0":"悬停","1":"着陆(降落)","2":"返航"} | 遥控器失控动作 | +| commander_mode_lost_action | 【必填】指点飞行失控动作 | enum_int | {"0":"继续执行指点飞行任务","1":"退出指点飞行任务,执行普通失控行为"} | | +| commander_flight_mode | 【必填】指点飞行模式设置值 | enum_int | {"0":"智能高度飞行","1":"设定高度飞行"} | | +| commander_flight_height | 【必填】指点飞行高度 | float | {"max":3000,"min":2,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT | +| flight_id | 一键起飞任务 UUID | text | | 任务 UUID,全局唯一,用于染色,云端区分该值是普通计划任务还是一键起飞任务 | +| max_speed | 一键起飞的飞行过程中能达到的最大速度 | int | {"max":15,"min":1,"unit_name":"米每秒 / m/s"} | | +| simulate_mission | 是否在模拟器中执行任务 | struct | | 可选字段,用于在室内进行模拟任务调试。 | +| »is_enable | 是否开启模拟器任务 | enum_int | {"0":"不开启","1":"开启"} | 当次任务打开或关闭模拟器 | +| »latitude | 纬度 | double | {"max":"90.0","min":"-90.0"} | | +| »longitude | 经度 | double | {"max":"180.0","min":"-180.0"} | | +| flight_safety_advance_check | 飞行安全预检查 | bool | {"0":"关闭","1":"开启"} | 设置一键起飞和航线任务中的飞行安全是否预先检查。此字段为可选,默认为0,值为0表示关闭,1表示开启。飞行安全预先检查表示: 飞行器执行任务前,检查自身作业区文件是否与云端一致,如果不一致则拉取文件更新,如果一致则不处理 | + +```json +{ + "data": { + "flight_id": flight_id, + "max_speed": 5, + "rc_lost_action": 2, + "rth_altitude": 60.0, + "rth_mode": 1, + "security_takeoff_height": 60.0, + "target_height": 70.0, + "target_latitude": 39.102603, + "target_longitude": 117.711972, + "commander_mode_lost_action": 0, + "commander_flight_mode": 1, + "commander_flight_height": 70.0, + "simulate_mission": { + }, + "flight_safety_advance_check": 0 + }, + "method": "takeoff_to_point" +} +``` + +### 飞向目标点: + +| fly_to_id | 飞向目标点 ID | text | | | +| --- | --- | --- | --- | --- | +| max_speed | flyto 的飞行过程中能达到的最大速度 | int | {"max":15,"min":0,"unit_name":"米每秒 / m/s"} | | +| points | flyto 目标点列表 | array | {"size": -, "item_type": struct} | 仅支持 1 个目标点 | +| »latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 | +| »longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 | +| »height | 目标点高度 | float | {"max":10000,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型 | + +```json +{ + "data": { + "fly_to_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx", + "max_speed": 12, + "points": [ + { + "height": 100, + "latitude": 12.23, + "longitude": 12.23 + } + ] + }, + "method": "fly_to_point" +} +``` + +### 结束飞向目标点: + +```json +{ + "data": {}, + "method": "fly_to_point_stop" +} +``` + +### 更新飞向目标点: + +| max_speed | 指令飞行过程中能达到的最大速度 | int | {"max":15,"min":1,"unit_name":"米每秒 / m/s"} | | +| --- | --- | --- | --- | --- | +| points | 更新的目标点列表 | array | {"size": -, "item_type": struct} | 仅支持 1 个目标点 | +| »latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 | +| »longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 | +| »height | 目标点高度 | float | {"max":10000,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型 | + +```json +{ + "data": { + "max_speed": 12, + "points": [ + { + "height": 100, + "latitude": 12.23, + "longitude": 12.23 + } + ] + }, + "method": "fly_to_point_update" +} +``` + +### 返航: + +```json +{ + "data": {}, + "method": "return_home" +} +``` diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/AgeDevice.java b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDevice.java new file mode 100644 index 00000000..0611d524 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDevice.java @@ -0,0 +1,49 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device") +public class AgeDevice extends SuperEntity { + + private String deviceSn; + private String deviceName; + private String userId; + private String nickname; + private String workspaceId; + private Integer deviceType; + private Integer subType; + private Integer domain; + private String firmwareVersion; + private Integer compatibleStatus; + private String version; + private String deviceIndex; + private String childSn; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + private Long boundTime; + private Integer boundStatus; + private Long loginTime; + private String deviceDesc; + private String urlNormal; + private String urlSelect; + private String tenantId; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java new file mode 100644 index 00000000..1f9e6ada --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDeviceFirmware.java @@ -0,0 +1,41 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device_firmware") +public class AgeDeviceFirmware extends SuperEntity { + private static final long serialVersionUID=1L; + + private String firmwareId; + private String fileName; + private String firmwareVersion; + private String objectKey; + private Long fileSize; + private String fileMd5; + private String workspaceId; + private String releaseNote; + private Long releaseDate; + private String userName; + private Integer status; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/AgeDeviceHms.java b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDeviceHms.java new file mode 100644 index 00000000..4137d1e2 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDeviceHms.java @@ -0,0 +1,38 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device_hms") +public class AgeDeviceHms extends SuperEntity { + private static final long serialVersionUID=1L; + + private String hmsId; + private String tid; + private String bid; + private String sn; + private Integer level; + private Integer module; + private String hmsKey; + private String messageZh; + private String messageEn; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/AgeDeviceLogs.java b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDeviceLogs.java new file mode 100644 index 00000000..89a3e500 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDeviceLogs.java @@ -0,0 +1,35 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device_logs") +public class AgeDeviceLogs extends SuperEntity { + private static final long serialVersionUID=1L; + + private String logsId; + private String username; + private String deviceSn; + private String logsInfo; + private Long happenTime; + private Integer status; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/AgeDevicePayload.java b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDevicePayload.java new file mode 100644 index 00000000..ffbdf5eb --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/AgeDevicePayload.java @@ -0,0 +1,38 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_device_payload") +public class AgeDevicePayload extends SuperEntity { + private static final long serialVersionUID=1L; + + private String payloadSn; + private String payloadName; + private Integer payloadType; + private Integer subType; + private String firmwareVersion; + private Integer payloadIndex; + private String deviceSn; + private String payloadDesc; + private String controlSource; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/AgeFirmwareModel.java b/zlt-business/device-center/src/main/java/com/central/device/model/AgeFirmwareModel.java new file mode 100644 index 00000000..ea19462f --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/AgeFirmwareModel.java @@ -0,0 +1,31 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_firmware_model") +public class AgeFirmwareModel extends SuperEntity { + private static final long serialVersionUID=1L; + + private String firmwareId; + private String deviceName; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/AgeWorkspace.java b/zlt-business/device-center/src/main/java/com/central/device/model/AgeWorkspace.java new file mode 100644 index 00000000..ce85a7cd --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/AgeWorkspace.java @@ -0,0 +1,34 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("manage_workspace") +public class AgeWorkspace extends SuperEntity { + private static final long serialVersionUID=1L; + + private String workspaceId; + private String workspaceName; + private String workspaceDesc; + private String platformName; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + private String bindCode; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/IaFile.java b/zlt-business/device-center/src/main/java/com/central/device/model/IaFile.java new file mode 100644 index 00000000..f10e5d7d --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/IaFile.java @@ -0,0 +1,41 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("media_file") +public class IaFile extends SuperEntity { + private static final long serialVersionUID=1L; + + private String fileId; + private String fileName; + private String filePath; + private String workspaceId; + private String fingerprint; + private String tinnyFingerprint; + private String objectKey; + private Integer subFileType; + private Integer isOriginal; + private String drone; + private String payload; + private String jobId; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/LineFile.java b/zlt-business/device-center/src/main/java/com/central/device/model/LineFile.java new file mode 100644 index 00000000..29240efa --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/LineFile.java @@ -0,0 +1,41 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("wayline_file") +public class LineFile extends SuperEntity { + private static final long serialVersionUID=1L; + + private String name; + private String waylineId; + private String droneModelKey; + private String payloadModelKeys; + private String workspaceId; + private String sign; + private Integer favorited; + private String templateTypes; + private String objectKey; + private String userName; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + private String tenantId; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/LineJob.java b/zlt-business/device-center/src/main/java/com/central/device/model/LineJob.java new file mode 100644 index 00000000..2ce273d0 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/LineJob.java @@ -0,0 +1,47 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("wayline_job") +public class LineJob extends SuperEntity { + private static final long serialVersionUID=1L; + + private String jobId; + private String name; + private String fileId; + private String dockSn; + private String workspaceId; + private Integer taskType; + private Integer waylineType; + private Long executeTime; + private Long completedTime; + private String username; + private Long beginTime; + private Long endTime; + private Integer errorCode; + private Integer status; + private Integer rthAltitude; + private Integer outOfControl; + private Integer mediaCount; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + private String parentId; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/SFile.java b/zlt-business/device-center/src/main/java/com/central/device/model/SFile.java new file mode 100644 index 00000000..2006dc7b --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/SFile.java @@ -0,0 +1,37 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("logs_file") +public class SFile extends SuperEntity { + private static final long serialVersionUID=1L; + + private String fileId; + private String name; + private Long size; + private String logsId; + private String deviceSn; + private String fingerprint; + private String objectKey; + private Integer status; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/SFileIndex.java b/zlt-business/device-center/src/main/java/com/central/device/model/SFileIndex.java new file mode 100644 index 00000000..1aed54a5 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/SFileIndex.java @@ -0,0 +1,36 @@ +package com.central.device.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.common.model.SuperEntity; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; +import java.util.Date; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("logs_file_index") +public class SFileIndex extends SuperEntity { + private static final long serialVersionUID=1L; + + private Integer bootIndex; + private String fileId; + private Long startTime; + private Long endTime; + private Long size; + private String deviceSn; + private Integer domain; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java b/zlt-business/device-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java new file mode 100644 index 00000000..2aed8665 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java @@ -0,0 +1,174 @@ +package com.central.device.model.excel; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.annotation.write.style.ColumnWidth; +import com.central.device.model.AgeDevice; +import com.fasterxml.jackson.annotation.JsonFormat; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +/** + * 设备信息Excel导入导出实体 + * + * @author lsl + * @date 2024-12-19 + */ +@Data +@EqualsAndHashCode(callSuper = false) +public class AgeDeviceExcel { + + @ExcelProperty(value = "设备序列号", index = 0) + @ColumnWidth(20) + @NotBlank(message = "设备序列号不能为空") + private String deviceSn; + + @ExcelProperty(value = "设备名称", index = 1) + @ColumnWidth(20) + @NotBlank(message = "设备名称不能为空") + private String deviceName; + + @ExcelProperty(value = "设备类型", index = 2) + @ColumnWidth(15) + private Integer deviceType; + + @ExcelProperty(value = "子类型", index = 3) + @ColumnWidth(15) + private Integer subType; + + @ExcelProperty(value = "固件版本", index = 4) + @ColumnWidth(20) + private String firmwareVersion; + + @ExcelProperty(value = "设备描述", index = 6) + @ColumnWidth(30) + private String deviceDesc; + + @ExcelProperty(value = "工作空间ID", index = 7) + @ColumnWidth(20) + private String workspaceId; + + @ExcelProperty(value = "域", index = 8) + @ColumnWidth(15) + private Integer domain; + + @ExcelProperty(value = "兼容状态", index = 9) + @ColumnWidth(15) + private Integer compatibleStatus; + + @ExcelProperty(value = "版本", index = 10) + @ColumnWidth(15) + private String version; + + @ExcelProperty(value = "设备索引", index = 11) + @ColumnWidth(20) + private String deviceIndex; + + @ExcelProperty(value = "子设备序列号", index = 12) + @ColumnWidth(20) + private String childSn; + + @ExcelProperty(value = "绑定状态", index = 13) + @ColumnWidth(15) + private Integer boundStatus; + + @ExcelProperty(value = "租户ID", index = 14) + @ColumnWidth(20) + private String tenantId; + + // 以下字段在Excel中不显示,但在实体转换时需要 + @ExcelIgnore + private String userId; + + @ExcelIgnore + private String nickname; + + @ExcelIgnore + private Long boundTime; + + @ExcelIgnore + private Long loginTime; + + @ExcelIgnore + private String urlNormal; + + @ExcelIgnore + private String urlSelect; + + @ExcelProperty(value = "创建时间", index = 15) + @ColumnWidth(20) + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date createTime; + + @ExcelProperty(value = "更新时间", index = 16) + @ColumnWidth(20) + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date updateTime; + + /** + * 转换为设备实体 + */ + public AgeDevice toDevice() { + AgeDevice device = new AgeDevice(); + // 必填字段 + device.setDeviceSn(this.deviceSn); + device.setDeviceName(this.deviceName); + device.setDeviceType(this.deviceType); + + // 可选字段,需要判空 + device.setSubType(this.subType); + device.setFirmwareVersion(this.firmwareVersion); + device.setDeviceDesc(this.deviceDesc); + device.setWorkspaceId(this.workspaceId); + device.setDomain(this.domain); + device.setCompatibleStatus(this.compatibleStatus); + device.setVersion(this.version); + device.setDeviceIndex(this.deviceIndex); + device.setChildSn(this.childSn); + device.setBoundStatus(this.boundStatus); + device.setTenantId(this.tenantId); + + // 系统字段 + device.setCreateTime(this.createTime); + device.setUpdateTime(this.updateTime); + + return device; + } + + /** + * 从设备实体转换 + */ + public static AgeDeviceExcel fromDevice(AgeDevice device) { + if (device == null) { + return null; + } + + AgeDeviceExcel excel = new AgeDeviceExcel(); + // 必填字段 + excel.setDeviceSn(device.getDeviceSn()); + excel.setDeviceName(device.getDeviceName()); + excel.setDeviceType(device.getDeviceType()); + + // 可选字段 + excel.setSubType(device.getSubType()); + excel.setFirmwareVersion(device.getFirmwareVersion()); + excel.setDeviceDesc(device.getDeviceDesc()); + excel.setWorkspaceId(device.getWorkspaceId()); + excel.setDomain(device.getDomain()); + excel.setCompatibleStatus(device.getCompatibleStatus()); + excel.setVersion(device.getVersion()); + excel.setDeviceIndex(device.getDeviceIndex()); + excel.setChildSn(device.getChildSn()); + excel.setBoundStatus(device.getBoundStatus()); + excel.setTenantId(device.getTenantId()); + + // 系统字段 + excel.setCreateTime(device.getCreateTime()); + excel.setUpdateTime(device.getUpdateTime()); + + return excel; + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java new file mode 100644 index 00000000..d02f41d8 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/DistributionDataVO.java @@ -0,0 +1,16 @@ +package com.central.device.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "分布数据") +public class DistributionDataVO { + @Schema(description = "类型") + private String type; + + @Schema(description = "数值") + private BigDecimal value; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java new file mode 100644 index 00000000..33c98966 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceFirmwareService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeDeviceFirmware; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IAgeDeviceFirmwareService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java new file mode 100644 index 00000000..ee8f1ceb --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceHmsService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeDeviceHms; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +public interface IAgeDeviceHmsService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java new file mode 100644 index 00000000..3fcc6be4 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceLogsService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeDeviceLogs; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +public interface IAgeDeviceLogsService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java new file mode 100644 index 00000000..91f3de0d --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDevicePayloadService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeDevicePayload; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +public interface IAgeDevicePayloadService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceService.java new file mode 100644 index 00000000..4f342ab7 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceService.java @@ -0,0 +1,44 @@ +package com.central.device.service; + +import com.central.device.model.AgeDevice; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.List; +import java.util.Map; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +public interface IAgeDeviceService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 根据参数查询设备列表 + */ + List findListByParams(Map params); + + /** + * 根据设备序列号查询设备 + */ + AgeDevice getByDeviceSn(String deviceSn); + + /** + * 检查设备序列号是否存在 + */ + boolean checkDeviceSnExists(String deviceSn); + + /** + * 批量导入设备信息 + */ + boolean importDevices(List deviceList); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java new file mode 100644 index 00000000..c2a674eb --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeFirmwareModelService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeFirmwareModel; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +public interface IAgeFirmwareModelService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java new file mode 100644 index 00000000..97375734 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IAgeWorkspaceService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.AgeWorkspace; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +public interface IAgeWorkspaceService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/IIaFileService.java b/zlt-business/device-center/src/main/java/com/central/device/service/IIaFileService.java new file mode 100644 index 00000000..8477e62a --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/IIaFileService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.IaFile; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +public interface IIaFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/ILineFileService.java b/zlt-business/device-center/src/main/java/com/central/device/service/ILineFileService.java new file mode 100644 index 00000000..5071320f --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/ILineFileService.java @@ -0,0 +1,25 @@ +package com.central.device.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.device.model.LineFile; + +import java.util.Map; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +public interface ILineFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + LineFile findLineFileByWaylineId(String waylineId); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/ILineJobService.java b/zlt-business/device-center/src/main/java/com/central/device/service/ILineJobService.java new file mode 100644 index 00000000..e7af5fc2 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/ILineJobService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.LineJob; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +public interface ILineJobService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/ISFileIndexService.java b/zlt-business/device-center/src/main/java/com/central/device/service/ISFileIndexService.java new file mode 100644 index 00000000..c05a71a5 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/ISFileIndexService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.SFileIndex; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +public interface ISFileIndexService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/ISFileService.java b/zlt-business/device-center/src/main/java/com/central/device/service/ISFileService.java new file mode 100644 index 00000000..6dc34343 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/ISFileService.java @@ -0,0 +1,23 @@ +package com.central.device.service; + +import com.central.device.model.SFile; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +public interface ISFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); +} + diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/LiveStreamService.java b/zlt-business/device-center/src/main/java/com/central/device/service/LiveStreamService.java new file mode 100644 index 00000000..851573d7 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/LiveStreamService.java @@ -0,0 +1,58 @@ +package com.central.device.service; + +import com.alibaba.fastjson.JSONObject; +import com.central.device.util.TencentLiveUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.util.concurrent.TimeUnit; + +@Service +public class LiveStreamService { + + @Value("${tencent.live.push-domain}") + private String pushDomain; + @Value("${tencent.live.play-domain}") + private String playDomain; + @Value("${tencent.live.app-name}") + private String appName; + @Value("${tencent.live.key}") + private String key; + @Value("${tencent.live.expire-seconds:3600}") + private long expireSeconds; + + private static final String STREAM_URL_KEY_PREFIX = "device:stream_urls:"; + + @Autowired + private StringRedisTemplate redisTemplate; + + /** + * 生成设备推流和拉流地址,并缓存到Redis + */ + public JSONObject generateStreamUrls(String deviceId) { + String cacheKey = STREAM_URL_KEY_PREFIX + deviceId; + String cacheValue = redisTemplate.opsForValue().get(cacheKey); + if (cacheValue != null) { + return JSONObject.parseObject(cacheValue); + } + + long expire = System.currentTimeMillis() / 1000 + expireSeconds; + String pushUrl = TencentLiveUtil.generatePushUrl(pushDomain, appName, deviceId, key, expire); + String playRtmpUrl = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "rtmp"); + String playFlvUrl = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "flv"); + String playM3u8Url = TencentLiveUtil.generatePlayUrl(playDomain, appName, deviceId, "m3u8"); + + JSONObject result = new JSONObject(); + result.put("pushUrl", pushUrl); + result.put("playRtmpUrl", playRtmpUrl); + result.put("playFlvUrl", playFlvUrl); + result.put("playM3u8Url", playM3u8Url); + + // 缓存到redis,设置过期时间(如1小时) + redisTemplate.opsForValue().set(cacheKey, result.toJSONString(), 1, TimeUnit.HOURS); + + return result; + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java new file mode 100644 index 00000000..99ffce09 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceFirmwareServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDeviceFirmwareMapper; +import com.central.device.model.AgeDeviceFirmware; +import com.central.device.service.IAgeDeviceFirmwareService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class AgeDeviceFirmwareServiceImpl extends SuperServiceImpl implements IAgeDeviceFirmwareService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java new file mode 100644 index 00000000..7061a557 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceHmsServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDeviceHmsMapper; +import com.central.device.model.AgeDeviceHms; +import com.central.device.service.IAgeDeviceHmsService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Device's hms information + * + * @author lsl + * @date 2024-12-19 17:53:01 + */ +@Slf4j +@Service +public class AgeDeviceHmsServiceImpl extends SuperServiceImpl implements IAgeDeviceHmsService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java new file mode 100644 index 00000000..fd7ad125 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceLogsServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDeviceLogsMapper; +import com.central.device.model.AgeDeviceLogs; +import com.central.device.service.IAgeDeviceLogsService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Log for uploading logs + * + * @author lsl + * @date 2024-12-19 17:53:03 + */ +@Slf4j +@Service +public class AgeDeviceLogsServiceImpl extends SuperServiceImpl implements IAgeDeviceLogsService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java new file mode 100644 index 00000000..555676c5 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDevicePayloadServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDevicePayloadMapper; +import com.central.device.model.AgeDevicePayload; +import com.central.device.service.IAgeDevicePayloadService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * The payload information of the device. + * + * @author lsl + * @date 2024-12-19 17:53:19 + */ +@Slf4j +@Service +public class AgeDevicePayloadServiceImpl extends SuperServiceImpl implements IAgeDevicePayloadService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java new file mode 100644 index 00000000..68ae00cd --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java @@ -0,0 +1,91 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeDeviceMapper; +import com.central.device.model.AgeDevice; +import com.central.device.service.IAgeDeviceService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.util.List; +import java.util.Map; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@Service +public class AgeDeviceServiceImpl extends SuperServiceImpl implements IAgeDeviceService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public List findListByParams(Map params) { + QueryWrapper wrapper = new QueryWrapper<>(); + // 添加查询条件 + if (params.get("deviceSn") != null) { + wrapper.like("device_sn", params.get("deviceSn")); + } + if (params.get("deviceName") != null) { + wrapper.like("device_name", params.get("deviceName")); + } + if (params.get("deviceType") != null) { + wrapper.eq("device_type", params.get("deviceType")); + } + // 可以添加更多查询条件... + return this.list(wrapper); + } + + @Override + public AgeDevice getByDeviceSn(String deviceSn) { + return this.getOne(new QueryWrapper().eq("device_sn", deviceSn)); + } + + @Override + public boolean checkDeviceSnExists(String deviceSn) { + return this.baseMapper.exists(new QueryWrapper() + .eq("device_sn", deviceSn)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public boolean importDevices(List deviceList) { + if (CollectionUtils.isEmpty(deviceList)) { + return false; + } + + try { + // 批量保存,每批100条 + int batchSize = 100; + int totalSize = deviceList.size(); + + for (int i = 0; i < totalSize; i += batchSize) { + int endIndex = Math.min(i + batchSize, totalSize); + List batch = deviceList.subList(i, endIndex); + this.saveBatch(batch, batchSize); + } + return true; + } catch (Exception e) { + log.error("批量导入设备信息失败", e); + throw new RuntimeException("批量导入设备信息失败", e); + } + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java new file mode 100644 index 00000000..c9f2485e --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeFirmwareModelServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeFirmwareModelMapper; +import com.central.device.model.AgeFirmwareModel; +import com.central.device.service.IAgeFirmwareModelService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:53:20 + */ +@Slf4j +@Service +public class AgeFirmwareModelServiceImpl extends SuperServiceImpl implements IAgeFirmwareModelService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java new file mode 100644 index 00000000..99c1c297 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeWorkspaceServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.AgeWorkspaceMapper; +import com.central.device.model.AgeWorkspace; +import com.central.device.service.IAgeWorkspaceService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * + * + * @author lsl + * @date 2024-12-19 17:52:26 + */ +@Slf4j +@Service +public class AgeWorkspaceServiceImpl extends SuperServiceImpl implements IAgeWorkspaceService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java new file mode 100644 index 00000000..23bd3271 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/IaFileServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.IaFileMapper; +import com.central.device.model.IaFile; +import com.central.device.service.IIaFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Media file information + * + * @author lsl + * @date 2024-12-19 17:52:18 + */ +@Slf4j +@Service +public class IaFileServiceImpl extends SuperServiceImpl implements IIaFileService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java new file mode 100644 index 00000000..50a65f8b --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java @@ -0,0 +1,43 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.LineFileMapper; +import com.central.device.model.LineFile; +import com.central.device.service.ILineFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Wayline file information + * + * @author lsl + * @date 2024-12-19 17:51:52 + */ +@Slf4j +@Service +public class LineFileServiceImpl extends SuperServiceImpl implements ILineFileService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public LineFile findLineFileByWaylineId(String waylineId) { + return baseMapper.selectOne(new QueryWrapper() + .eq("wayline_id",waylineId)); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java new file mode 100644 index 00000000..8f3b1c95 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/LineJobServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.LineJobMapper; +import com.central.device.model.LineJob; +import com.central.device.service.ILineJobService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Wayline mission information of the dock. + * + * @author lsl + * @date 2024-12-19 17:51:53 + */ +@Slf4j +@Service +public class LineJobServiceImpl extends SuperServiceImpl implements ILineJobService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java new file mode 100644 index 00000000..40ec93b1 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/SFileIndexServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.SFileIndexMapper; +import com.central.device.model.SFileIndex; +import com.central.device.service.ISFileIndexService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * The boot index table corresponding to the logs file. + * + * @author lsl + * @date 2024-12-19 17:53:23 + */ +@Slf4j +@Service +public class SFileIndexServiceImpl extends SuperServiceImpl implements ISFileIndexService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java new file mode 100644 index 00000000..3d508db3 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/SFileServiceImpl.java @@ -0,0 +1,36 @@ +package com.central.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.device.mapper.SFileMapper; +import com.central.device.model.SFile; +import com.central.device.service.ISFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Logs file information + * + * @author lsl + * @date 2024-12-19 17:53:36 + */ +@Slf4j +@Service +public class SFileServiceImpl extends SuperServiceImpl implements ISFileService { + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/IotRequestResult.java b/zlt-business/device-center/src/main/java/com/central/device/util/IotRequestResult.java new file mode 100644 index 00000000..b0dffef1 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/IotRequestResult.java @@ -0,0 +1,37 @@ +package com.central.device.util; + +import com.alibaba.fastjson.JSONObject; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * IOT request result model + * @author lsl + * @date 2025-02-25 + * + */ +@Setter +@Getter +public class IotRequestResult { + + private String message; + private Integer status; + private Long timestamp; + private String code; + private List result; + + public static IotRequestResult getInstance(JSONObject message) throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + + // 将JSONObject转换为JsonNode,因为ObjectMapper不直接接受JSONObject + JsonNode jsonNode = objectMapper.readTree(message.toString()); + + // 将JsonNode转换为指定的Java类 + return objectMapper.treeToValue(jsonNode, IotRequestResult.class); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/MapUtil.java b/zlt-business/device-center/src/main/java/com/central/device/util/MapUtil.java new file mode 100644 index 00000000..d86a6208 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/MapUtil.java @@ -0,0 +1,52 @@ +package com.central.device.util; + +import java.util.Map; + +/** + * 获取map各类型值工具类 + * @author lishilin + * @date 2020/03/12 + */ +public class MapUtil { + public static String getStrValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + return val.toString(); + } + + public static Integer getIntValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + try { + return Integer.parseInt(param.get(id).toString()); + } catch (NumberFormatException exp) { + return null; + } + } + + public static Long getLongValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + try { + return Long.parseLong(param.get(id).toString()); + } catch (NumberFormatException exp) { + return null; + } + } + + public static Object getValue(Map param, String id) { + if (null == param && null == id) { + return null; + } + if (param.containsKey(id)) { + return param.get(id); + } + return null; + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/RequestUtils.java b/zlt-business/device-center/src/main/java/com/central/device/util/RequestUtils.java new file mode 100644 index 00000000..f59b5422 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/RequestUtils.java @@ -0,0 +1,118 @@ +package com.central.device.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.central.device.util.http.HeaderUtils; +import com.central.device.util.http.HttpRequest; +import com.central.device.util.http.Response; +import com.central.device.util.http.SimpleHttpRequest; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.Map; + +/** + * @author LSL + */ +@Slf4j +@Component +public class RequestUtils { + + @Autowired + private HeaderUtils headerUtils; + + /** + * 获取post请求result + * @param url 请求url + * @param jsonObject 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, JSONObject jsonObject) throws IOException { + log.debug(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(jsonObject.toJSONString())); + request.requestBody(jsonObject.toJSONString()); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param param 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, Map param) throws IOException { + log.debug(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param body 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, String body) throws IOException { + log.debug(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(body)); + request.requestBody(body); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + log.debug(""+result.get("")); + return result; + } + + /** + * @param url 请求url + * @param map 请求参数map + * @return + * @throws IOException + */ + public Map getGetRequestResultMap(String url,Map map) throws IOException { + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfParams(map)); + + Response response = request.get(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param param 请求参数 + * @return + * @throws IOException + */ + public Map getThirdPartyPostRequestResultMap(String url, Map param) { + log.info("url:{} , {}",url,param); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + Response response; + Map result = null; + try { + response = request.post(); + result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + } catch (IOException e) { + log.info("查询异常:{}",e.getMessage()); + e.printStackTrace(); + } + return result; + } + + +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/TencentLiveUtil.java b/zlt-business/device-center/src/main/java/com/central/device/util/TencentLiveUtil.java new file mode 100644 index 00000000..13250dfa --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/TencentLiveUtil.java @@ -0,0 +1,30 @@ +package com.central.device.util; + +import org.apache.commons.codec.digest.DigestUtils; + +public class TencentLiveUtil { + + /** + * 生成推流地址 + */ + public static String generatePushUrl(String pushDomain, String appName, String streamName, String key, long expireTime) { + String txTime = Long.toHexString(expireTime).toUpperCase(); + String txSecret = DigestUtils.md5Hex(key + streamName + txTime).toLowerCase(); + return String.format("rtmp://%s/%s/%s?txSecret=%s&txTime=%s", pushDomain, appName, streamName, txSecret, txTime); + } + + /** + * 生成拉流地址 + */ + public static String generatePlayUrl(String playDomain, String appName, String streamName, String type) { + switch (type.toLowerCase()) { + case "flv": + return String.format("http://%s/%s/%s.flv", playDomain, appName, streamName); + case "m3u8": + return String.format("http://%s/%s/%s.m3u8", playDomain, appName, streamName); + case "rtmp": + default: + return String.format("rtmp://%s/%s/%s", playDomain, appName, streamName); + } + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/Utils.java b/zlt-business/device-center/src/main/java/com/central/device/util/Utils.java new file mode 100644 index 00000000..fc2af9a5 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/Utils.java @@ -0,0 +1,47 @@ +package com.central.device.util; + +import java.io.*; +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.Map; + +/** + * @author lishilin + * @see + * @since 2.0 + */ +public class Utils { + public static Map queryStringToMap(String queryString, String charset){ + try { + Map map = new HashMap<>(); + + String[] decode = URLDecoder.decode(queryString,charset).split("&"); + for (String keyValue : decode) { + String[] kv = keyValue.split("[=]",2); + map.put(kv.length>1?kv[1]:"",kv[0]); + } + return map; + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException(e); + } + } + + /** + * 读文件 + * + * @param file 文件 + * @return + * @throws IOException + * @throws IOException + */ + public static String readTxt(File file) throws IOException { + String s = ""; + InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"); + BufferedReader br = new BufferedReader(in); + StringBuffer content = new StringBuffer(); + while ((s = br.readLine()) != null) { + content = content.append(s); + } + return content.toString(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/http/HeaderUtils.java b/zlt-business/device-center/src/main/java/com/central/device/util/http/HeaderUtils.java new file mode 100644 index 00000000..c066c6d5 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/http/HeaderUtils.java @@ -0,0 +1,81 @@ +package com.central.device.util.http; + +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.codec.digest.DigestUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Collectors; + +/** + * @author lishilin + * @see + * @since 1.0 + */ +@Component +public class HeaderUtils { + + @Value("${jetlinks.clientId}") + private String xClientId;// = "WFMfEGS8iHrEPRBH" ; + + @Value("${jetlinks.secureKey}") + private String secureKey;// = "ihat3zHC6T7xPZYFAEnG3tExQiFANd2n" ; + public Map createHeadersOfParams(Map params) { + //时间戳 + String xTimestamp = String.valueOf(System.currentTimeMillis()); + //openApi客户端id +// String xClientId = "rN7cpmQb884W4hcH"; + //密钥 +// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; + //将参数按ASCII排序后拼接为k1=v1&k2=v2的格式 + String paramString = new TreeMap<>(params).entrySet() + .stream() + .map(e -> e.getKey().concat("=").concat(String.valueOf(e.getValue()))) + .collect(Collectors.joining("&")); + + System.out.println(paramString); + + //param+X-Timestamp+SecureKey通过MD5加密 + MessageDigest digest = DigestUtils.getMd5Digest(); + System.out.println(paramString + xTimestamp + secureKey); + digest.update(paramString.getBytes()); + digest.update(xTimestamp.getBytes()); + digest.update(secureKey.getBytes()); + + Map headers = new HashMap<>(); + headers.put("X-Sign", Hex.encodeHexString(digest.digest())); + headers.put("X-Client-Id", xClientId); + headers.put("X-Timestamp", xTimestamp); + + return headers; + } + + + public Map createHeadersOfJsonString(String jsonString) { + //时间戳 + String xTimestamp = String.valueOf(System.currentTimeMillis()); + //openApi客户端id +// String xClientId = "rN7cpmQb884W4hcH"; + //密钥 +// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; + + + //param+X-Timestamp+SecureKey通过MD5加密 + MessageDigest digest = DigestUtils.getMd5Digest(); + System.out.println(jsonString + xTimestamp + secureKey); + digest.update(jsonString.getBytes()); + digest.update(xTimestamp.getBytes()); + digest.update(secureKey.getBytes()); + + Map headers = new HashMap<>(5); + headers.put("X-Sign", Hex.encodeHexString(digest.digest())); + headers.put("X-Client-Id", xClientId); + headers.put("X-Timestamp", xTimestamp); + + return headers; + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/http/HttpRequest.java b/zlt-business/device-center/src/main/java/com/central/device/util/http/HttpRequest.java new file mode 100644 index 00000000..595298df --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/http/HttpRequest.java @@ -0,0 +1,39 @@ +package com.central.device.util.http; + +import java.io.Closeable; +import java.io.IOException; +import java.util.Map; + +/** + * @author wang + * @see + * @since 1.0 + */ +public interface HttpRequest extends Closeable { + + Response get() throws IOException; + + Response post() throws IOException; + + Response put() throws IOException; + + Response delete() throws IOException; + + Response patch() throws IOException; + + HttpRequest encode(String encode); + + HttpRequest contentType(String type); + + HttpRequest param(String name, String value); + + HttpRequest params(Map params); + + HttpRequest header(String name, String value); + + HttpRequest headers(Map headers); + + HttpRequest requestBody(String body); + + HttpRequest resultAsJsonString(); +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/http/Response.java b/zlt-business/device-center/src/main/java/com/central/device/util/http/Response.java new file mode 100644 index 00000000..628d7faf --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/http/Response.java @@ -0,0 +1,13 @@ +package com.central.device.util.http; + +import java.io.IOException; + +/** + * @author wang + * @see + * @since 1.0 + */ +public interface Response { + + byte[] asBytes() throws IOException; +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java b/zlt-business/device-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java new file mode 100644 index 00000000..d48136fe --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/http/SimpleHttpRequest.java @@ -0,0 +1,184 @@ +package com.central.device.util.http; + +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.*; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author wang + * @see + * @since 1.0 + */ +public class SimpleHttpRequest implements HttpRequest { + + private Map params = new LinkedHashMap<>(); + private Map headers = new LinkedHashMap<>(); + private String url; + private String requestBody; + private String contentType; + private String encode = "utf-8"; + protected HttpClient httpClient; + + public SimpleHttpRequest(String url) { + this.url = url; + createHttpClient(); + } + + public SimpleHttpRequest(String url, HttpClient client) { + this.url = url; + this.httpClient = client; + } + + protected void createHttpClient() { + if (httpClient == null) { + HttpClientBuilder builder = HttpClientBuilder.create(); + httpClient = builder.build(); + + } + } + + @Override + public Response get() throws IOException { + String param = EntityUtils.toString(createUrlEncodedFormEntity()); + String tmpUrl = url + (url.contains("?") ? "&" : "?") + param; + HttpGet get = new HttpGet(tmpUrl); + HttpResponse response = execute(get); + return getResultValue(response); + } + + + @Override + public Response post() throws IOException { + HttpPost post = new HttpPost(url); + if (requestBody != null) + post.setEntity(new StringEntity(requestBody, ContentType.create(contentType,encode))); + else { + post.setEntity(createUrlEncodedFormEntity()); + } + HttpResponse response = execute(post); + return getResultValue(response); + } + + @Override + public Response put() throws IOException { + HttpPut put = new HttpPut(url); + if (requestBody != null) + put.setEntity(new StringEntity(requestBody, ContentType.create(contentType, encode))); + else { + + put.setEntity(createUrlEncodedFormEntity()); + } + HttpResponse response = execute(put); + return getResultValue(response); + } + + protected UrlEncodedFormEntity createUrlEncodedFormEntity() throws UnsupportedEncodingException { + List nameValuePair = params.entrySet() + .stream().map(stringStringEntry -> + new BasicNameValuePair(stringStringEntry.getKey(), String.valueOf(stringStringEntry.getValue()))) + .collect(Collectors.toList()); + return new UrlEncodedFormEntity(nameValuePair, encode); + } + + @Override + public Response delete() throws IOException { + HttpDelete delete = new HttpDelete(url); + HttpResponse response = execute(delete); + return getResultValue(response); + } + + @Override + public Response patch() throws IOException { + HttpPatch delete = new HttpPatch(url); + if (requestBody != null) + delete.setEntity(new StringEntity(requestBody, ContentType.create(contentType))); + else { + delete.setEntity(createUrlEncodedFormEntity()); + } + return getResultValue(execute(delete)); + } + + @Override + public void close() throws IOException { + if (httpClient != null && httpClient instanceof CloseableHttpClient) { + ((CloseableHttpClient) httpClient).close(); + } + } + + @Override + public HttpRequest resultAsJsonString() { + header("Accept", "application/json"); + return this; + } + + @Override + public HttpRequest requestBody(String body) { + contentType("application/json"); + this.requestBody = body; + return this; + } + + @Override + public HttpRequest encode(String encode) { + this.encode = encode; + return this; + } + + @Override + public HttpRequest contentType(String type) { + this.contentType = type; + return this; + } + + @Override + public HttpRequest param(String name, String value) { + this.params.put(name, value); + return this; + } + + @Override + public HttpRequest params(Map params) { + this.params.putAll(params); + return this; + } + + @Override + public HttpRequest header(String name, String value) { + this.headers.put(name, value); + return this; + } + + @Override + public HttpRequest headers(Map header) { + this.headers.putAll(header); + return this; + } + + private Response getResultValue(HttpResponse res) throws IOException { + return new SimpleResponse(res); + } + + private HttpResponse execute(HttpRequestBase request) throws IOException { + putHeader(request); + return httpClient.execute(request); + } + + private void putHeader(HttpUriRequest request) { + headers.forEach(request::setHeader); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/util/http/SimpleResponse.java b/zlt-business/device-center/src/main/java/com/central/device/util/http/SimpleResponse.java new file mode 100644 index 00000000..6444f876 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/util/http/SimpleResponse.java @@ -0,0 +1,26 @@ +package com.central.device.util.http; + +import org.apache.http.HttpResponse; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; + +/** + * @author wang + * @see + * @since 1.0 + */ +public class SimpleResponse implements Response { + + HttpResponse response; + + public SimpleResponse(HttpResponse response) { + this.response = response; + } + + + @Override + public byte[] asBytes() throws IOException { + return EntityUtils.toByteArray(response.getEntity()); + } +} diff --git a/zlt-business/device-center/src/main/resources/application.yml b/zlt-business/device-center/src/main/resources/application.yml new file mode 100644 index 00000000..32f0c2e5 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/application.yml @@ -0,0 +1,59 @@ +spring: + datasource: +# url: jdbc:mysql://${zlt.datasource.ip}:3306/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + url: jdbc:mysql://${zlt.datasource.ip}/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + username: ${zlt.datasource.username} + password: ${zlt.datasource.password} + driver-class-name: com.mysql.cj.jdbc.Driver + +mybatis-plus: + mapper-locations: classpath:/mapper/*Mapper.xml + #实体扫描,多个package用逗号或者分号分隔 + typeAliasesPackage: com.central.device.model + global-config: + db-config: + id-type: auto + +springdoc: + group-configs: + - group: 'default' + paths-to-match: '/**' + packages-to-scan: com.central.device.controller + +knife4j: + enable: true + setting: + swagger-model-name: 设备中心接口文档 + +jetlinks: + clientId: WFMfEGS8iHrEPRBH + secureKey: ihat3zHC6T7xPZYFAEnG3tExQiFANd2n + server: + baseUrl: http://119.45.169.13:8848/ + + #审计日志 +# audit-log: +# enabled: true +# log-type: db +# datasource: +# driver-class-name: com.mysql.cj.jdbc.Driver +# jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai +# username: ${zlt.datasource.username} +# password: ${zlt.datasource.password} +tencent: + live: + push-domain: 208280.push.tlivecloud.com + play-domain: goflytec.com + expire-seconds: 3600 #过期时间为1小时 + app-name: live + key: 06b20e5b7d637c1128fa1b48ea91a13e + +zlt: + #多租户配置 + tenant: + enable: false + ignoreTables: + ignoreSqls: + noIgnoreSqls: + - com.central.device.mapper.AgeDeviceMapper.findList + - com.central.device.mapper.LineFileMapper.findList diff --git a/zlt-business/device-center/src/main/resources/bootstrap.yml b/zlt-business/device-center/src/main/resources/bootstrap.yml new file mode 100644 index 00000000..1a0e7044 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/bootstrap.yml @@ -0,0 +1,15 @@ +server: + port: 7001 + +spring: + application: + name: device-center + cloud: + nacos: + discovery: + ip: 119.45.169.13 +# cloud: +# nacos: +# discovery: +# metadata: +# version: zlt diff --git a/zlt-business/device-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml b/zlt-business/device-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml new file mode 100644 index 00000000..33de4e1c --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/AgeDeviceFirmwareMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml b/zlt-business/device-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml new file mode 100644 index 00000000..2bcf9d0b --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/AgeDeviceHmsMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml b/zlt-business/device-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml new file mode 100644 index 00000000..09722eb0 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/AgeDeviceLogsMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/AgeDeviceMapper.xml b/zlt-business/device-center/src/main/resources/mapper/AgeDeviceMapper.xml new file mode 100644 index 00000000..efa174ba --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/AgeDeviceMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml b/zlt-business/device-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml new file mode 100644 index 00000000..ea9fd213 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/AgeDevicePayloadMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml b/zlt-business/device-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml new file mode 100644 index 00000000..32e77875 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/AgeFirmwareModelMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/AgeWorkspaceMapper.xml b/zlt-business/device-center/src/main/resources/mapper/AgeWorkspaceMapper.xml new file mode 100644 index 00000000..9ba31ce1 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/AgeWorkspaceMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/IaFileMapper.xml b/zlt-business/device-center/src/main/resources/mapper/IaFileMapper.xml new file mode 100644 index 00000000..4e6723cd --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/IaFileMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/LineFileMapper.xml b/zlt-business/device-center/src/main/resources/mapper/LineFileMapper.xml new file mode 100644 index 00000000..b5fcb3e5 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/LineFileMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/LineJobMapper.xml b/zlt-business/device-center/src/main/resources/mapper/LineJobMapper.xml new file mode 100644 index 00000000..b498a16d --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/LineJobMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/SFileIndexMapper.xml b/zlt-business/device-center/src/main/resources/mapper/SFileIndexMapper.xml new file mode 100644 index 00000000..38f304e6 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/SFileIndexMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/device-center/src/main/resources/mapper/SFileMapper.xml b/zlt-business/device-center/src/main/resources/mapper/SFileMapper.xml new file mode 100644 index 00000000..3b2002ce --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/SFileMapper.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/zlt-business/file-center/pom.xml b/zlt-business/file-center/pom.xml index 62e32722..d7fefb8a 100644 --- a/zlt-business/file-center/pom.xml +++ b/zlt-business/file-center/pom.xml @@ -80,15 +80,35 @@ fastdfs-client --> - + + + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + javax.activation + activation + 1.1.1 + + + + org.glassfish.jaxb + jaxb-runtime + 2.3.3 org.hibernate hibernate-validator + @@ -132,4 +152,4 @@ ${project.artifactId} - \ No newline at end of file + diff --git a/zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java b/zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java index 93c784f9..9b6a83f3 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java +++ b/zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java @@ -1,32 +1,50 @@ package com.central.file.controller; -import java.util.Map; - +import com.central.common.model.FileInfo; +import com.central.common.model.PageResult; import com.central.common.model.Result; import com.central.file.service.IFileService; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.*; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; -import com.central.common.model.PageResult; -import com.central.file.model.FileInfo; - -import javax.annotation.Resource; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; /** * 文件上传 * * @author 作者 owen E-mail: 624191343@qq.com */ +@Slf4j @RestController public class FileController { - @Resource + @Autowired private IFileService fileService; + @Value("${zlt.security.tencent.accessTokenUrl}") + private String accessTokenUrl; + + @Value("${zlt.security.tencent.getwxacodeUrl}") + private String getwxacodeUrl; + + private RestTemplate restTemplate = new RestTemplate(); + + @Value("${zlt.security.tencent.pagePath}") + private Object pagePath; + /** * 文件上传 * 根据fileType选择上传方式 @@ -35,11 +53,25 @@ public class FileController { * @return * @throws Exception */ - @PostMapping("/files-anon") + @PostMapping(value = "/files-anon",consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public FileInfo upload(@RequestParam("file") MultipartFile file) throws Exception { return fileService.upload(file); } + /** + * 文件上传 + * 根据fileType选择上传方式 + * + * @param file + * @return + * @throws Exception + */ + @PostMapping(value = "/files-anon/file",consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception { + FileInfo fileInfo = fileService.upload(file); + return fileService.getViewUrlByPath(fileInfo.getPath()); + } + /** * 文件删除 * @@ -63,6 +95,132 @@ public class FileController { */ @GetMapping("/files") public PageResult findFiles(@RequestParam Map params) { - return fileService.findList(params); + PageResult pageResult = fileService.findList(params); + if(pageResult.getCount() >0){ + for (FileInfo fileInfo: pageResult.getData()){ + fileInfo.setUrl(getViewUrlByPath(fileInfo.getName())); + } + } + return pageResult; + } + + @GetMapping("/file/{id}") + public String getFileViewUrl(@PathVariable String id) { + log.info("请求文件可访问链接,参数文件Id:{}",id); + String viewUrl = fileService.getViewUrl(id); + log.info("请求文件可访问链接,链接值:{}",viewUrl); + return viewUrl; + } + + @GetMapping("/files/{id}") + public Result getViewUrl(@PathVariable String id) { + return Result.succeed(fileService.getViewUrl(id),"获取成功"); + } + + @GetMapping("/file/path") + public Result getFileViewUrlByPath(@RequestParam String path) { + return Result.succeed(fileService.getViewUrlByPath(path),"获取成功"); + } + + @GetMapping("/files/path") + public String getViewUrlByPath(@RequestParam String path) { + return fileService.getViewUrlByPath(path); + } + + @GetMapping("/files/path/style") + public String getViewUrlByPathStyle(@RequestParam Map params) { + return fileService.getZipViewUrlByPath(MapUtils.getString(params,"path"),MapUtils.getString(params, "style")); + } + + @GetMapping("/type/{id}") + public String getFileInfo(@PathVariable String id) { + FileInfo fileInfo = fileService.getFileInfo(id); + if (fileInfo != null) { + return fileInfo.getContentType(); + } + return "image/png"; + } + + @GetMapping("/qrcode/{codeId}") + public Result uploadQrCodeFile(@PathVariable("codeId") String codeId) throws Exception { + Map map = new LinkedHashMap<>(); + String accessToken = getAccessTokenUrl(); + + FileInfo fileInfo = fileService.upload(codeId+".jpeg",getQRCode(accessToken,codeId)); + map.put("codeId", codeId); + map.put("fileId", fileInfo.getId()); + map.put("filePath", fileInfo.getPath()); + return Result.succeed(map); + } + + @PostMapping("/path") + FileInfo creatFileInfo(@RequestBody String path){ + return fileService.createFile(path); + } + + /** + * 获取access_token + * @return + */ + public String getAccessTokenUrl() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED); + MultiValueMap params = new LinkedMultiValueMap<>(); + HttpEntity> requestEntity = new HttpEntity<>(params, headers); + ResponseEntity responseEntity = restTemplate.exchange(accessTokenUrl, HttpMethod.GET, requestEntity, String.class); + + if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody().contains("access_token")) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + Map map = objectMapper.readValue(responseEntity.getBody(), Map.class); + return (String) map.get("access_token"); + } catch (Exception e) { + return ""; + } + }else { + return ""; + } + + } + + /** + * 获取qrcode + * + * @return + */ + public InputStream getQRCode(String accessToken, String codeId) { + String url = getwxacodeUrl + accessToken; // 确保这里拼接正确,可能还需要其他参数 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + Map requestBody = new HashMap<>(); + requestBody.put("path", pagePath + codeId); + HttpEntity requestEntity = new HttpEntity<>(requestBody, headers); + ResponseEntity responseEntity = restTemplate.exchange( + getwxacodeUrl+accessToken, // 假设path参数是这样传递的 + HttpMethod.POST, // 或者POST,取决于API要求 + requestEntity, + byte[].class); // 直接请求二进制数据 + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + byte[] qrCodeBytes = responseEntity.getBody(); + // 这里可以直接将字节数组转换为InputStream并返回,或者上传到OSS + InputStream qrCodeStream = new ByteArrayInputStream(qrCodeBytes); + return qrCodeStream; // 如果确实需要返回InputStream,则这样返回 + } else { + throw new RuntimeException("Failed to fetch QR code: " + responseEntity.getStatusCode()); + } + } + + @GetMapping("/list/files") + public List getListFiles(@RequestParam String prefix) { + + return fileService.listFiles(prefix); + } + + @GetMapping("/file/expires") + public String getFileViewUrlForExpires(@RequestParam("id") String id) { + String viewUrl = fileService.getViewUrlByPathAndExpires(id,3600*3000); + return viewUrl; } } diff --git a/zlt-business/file-center/src/main/java/com/central/file/mapper/FileMapper.java b/zlt-business/file-center/src/main/java/com/central/file/mapper/FileMapper.java index 00c1efc5..1013700a 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/mapper/FileMapper.java +++ b/zlt-business/file-center/src/main/java/com/central/file/mapper/FileMapper.java @@ -1,15 +1,14 @@ package com.central.file.mapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.FileInfo; +import com.central.db.mapper.SuperMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + import java.util.List; import java.util.Map; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.db.mapper.SuperMapper; - -import com.central.file.model.FileInfo; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; - /** * 上传存储db * @@ -18,4 +17,6 @@ import org.apache.ibatis.annotations.Param; @Mapper public interface FileMapper extends SuperMapper { List findList(Page page, @Param("f") Map params); + + FileInfo findById(@Param("id") String id); } diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/IFileService.java b/zlt-business/file-center/src/main/java/com/central/file/service/IFileService.java index 2e44595f..c8b63bc4 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/service/IFileService.java +++ b/zlt-business/file-center/src/main/java/com/central/file/service/IFileService.java @@ -1,13 +1,14 @@ package com.central.file.service; -import java.io.OutputStream; -import java.util.Map; - import com.baomidou.mybatisplus.extension.service.IService; +import com.central.common.model.FileInfo; import com.central.common.model.PageResult; import org.springframework.web.multipart.MultipartFile; -import com.central.file.model.FileInfo; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; /** * 文件service @@ -16,10 +17,26 @@ import com.central.file.model.FileInfo; */ public interface IFileService extends IService { FileInfo upload(MultipartFile file ) throws Exception; - + + FileInfo upload(String name, InputStream inputStream) throws Exception; + PageResult findList(Map params); void delete(String id); void out(String id, OutputStream os); + + String getViewUrl(String id); + + String getViewUrlByPath(String name); + + String getZipViewUrlByPath(String name, String style); + + FileInfo getFileInfo(String id); + + FileInfo createFile(String path); + + List listFiles(String prefix); + + String getViewUrlByPathAndExpires(String name,int expires); } diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/impl/AbstractIFileService.java b/zlt-business/file-center/src/main/java/com/central/file/service/impl/AbstractIFileService.java index 93e38e1e..d38be674 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/service/impl/AbstractIFileService.java +++ b/zlt-business/file-center/src/main/java/com/central/file/service/impl/AbstractIFileService.java @@ -1,21 +1,21 @@ package com.central.file.service.impl; -import java.util.List; -import java.util.Map; - import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.central.common.model.FileInfo; +import com.central.common.model.PageResult; +import com.central.file.mapper.FileMapper; +import com.central.file.service.IFileService; +import com.central.file.utils.FileUtil; import com.central.oss.model.ObjectInfo; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; import org.springframework.web.multipart.MultipartFile; -import com.central.common.model.PageResult; -import com.central.file.mapper.FileMapper; -import com.central.file.model.FileInfo; -import com.central.file.service.IFileService; -import com.central.file.utils.FileUtil; - -import lombok.extern.slf4j.Slf4j; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; /** * AbstractIFileService 抽取类 @@ -44,6 +44,23 @@ public abstract class AbstractIFileService extends ServiceImpl findList(Map params) { Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).code(0).count(page.getTotal()).build(); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + public abstract String getViewUrlByPath(String name); + + @Override + public FileInfo getFileInfo(String id) { + return baseMapper.selectById(id); } } diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/impl/CosService.java b/zlt-business/file-center/src/main/java/com/central/file/service/impl/CosService.java new file mode 100644 index 00000000..d121bac3 --- /dev/null +++ b/zlt-business/file-center/src/main/java/com/central/file/service/impl/CosService.java @@ -0,0 +1,113 @@ +package com.central.file.service.impl; + +import cn.hutool.core.util.StrUtil; +import com.central.common.constant.CommonConstant; +import com.central.common.model.FileInfo; +import com.central.oss.model.ObjectInfo; +import com.central.oss.properties.FileServerProperties; +import com.central.oss.template.CosTemplate; +import com.qcloud.cos.model.COSObject; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; + +/** + * @author lsl + * @date 2025/1/13 + *

+ */ +@Service +@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_COS) +public class CosService extends AbstractIFileService { + + @Resource + private CosTemplate cosTemplate; + + @Override + protected String fileType() { + return FileServerProperties.TYPE_COS; + } + + @Override + protected ObjectInfo uploadFile(MultipartFile file) { + return cosTemplate.upload(file); + } + + @Override + protected ObjectInfo uploadFile(String name, InputStream inputStream) throws IOException { + return cosTemplate.upload(name, inputStream,inputStream.available(),"image/jpeg"); + } + + @Override + protected void deleteFile(String objectPath) { + COSObject cosObject = parsePath(objectPath); + cosTemplate.delete(cosObject.getBucketName(), cosObject.getKey()); + } + + @Override + public String getViewUrlByPath(String name) { + return ""; + } + + @Override + public String getZipViewUrlByPath(String name, String style) { + return ""; + } + + @Override + public void out(String id, OutputStream os) { + FileInfo fileInfo = baseMapper.selectById(id); + if (fileInfo != null) { + COSObject cosObject = parsePath(fileInfo.getPath()); + cosTemplate.out(cosObject.getBucketName(), cosObject.getKey(), os); + } + } + + @Override + public String getViewUrl(String fileId) { + FileInfo fileInfo = baseMapper.selectById(fileId); + if (fileInfo != null) { + return cosTemplate.getViewUrl(fileInfo.getName()); + } + return null; + } + + @Override + public FileInfo getFileInfo(String id) { + return baseMapper.selectById(id); + } + + @Override + public FileInfo createFile(String path) { + return null; + } + + @Override + public List listFiles(String prefix) { + return List.of(); + } + + @Override + public String getViewUrlByPathAndExpires(String name, int expires) { + return ""; + } + + private COSObject parsePath(String path) { + COSObject cosObject = new COSObject(); + if (StrUtil.isNotEmpty(path)) { + int splitIndex = path.lastIndexOf(CommonConstant.PATH_SPLIT); + if (splitIndex != -1) { + cosObject.setBucketName(path.substring(0, splitIndex)); + cosObject.setKey(path.substring(splitIndex + 1)); + } + } + return cosObject; + } + +} diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/impl/FastdfsService.java b/zlt-business/file-center/src/main/java/com/central/file/service/impl/FastdfsService.java index a931af9a..64ee5b98 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/service/impl/FastdfsService.java +++ b/zlt-business/file-center/src/main/java/com/central/file/service/impl/FastdfsService.java @@ -1,5 +1,6 @@ package com.central.file.service.impl; +import com.central.common.model.FileInfo; import com.central.oss.model.ObjectInfo; import com.central.oss.properties.FileServerProperties; import com.central.oss.template.FdfsTemplate; @@ -8,7 +9,9 @@ import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; +import java.io.InputStream; import java.io.OutputStream; +import java.util.List; /** * @author zlt @@ -33,12 +36,52 @@ public class FastdfsService extends AbstractIFileService { return fdfsTemplate.upload(file); } + @Override + protected ObjectInfo uploadFile(String name, InputStream inputStream) { + return null; + } + @Override protected void deleteFile(String objectPath) { fdfsTemplate.delete(objectPath); } + @Override + public String getViewUrlByPath(String name) { + return ""; + } + + @Override + public String getZipViewUrlByPath(String name, String style) { + return ""; + } + @Override public void out(String id, OutputStream os) { } + + @Override + public String getViewUrl(String id) { + return ""; + } + + @Override + public FileInfo getFileInfo(String id) { + return null; + } + + @Override + public FileInfo createFile(String path) { + return null; + } + + @Override + public List listFiles(String prefix) { + return List.of(); + } + + @Override + public String getViewUrlByPathAndExpires(String name, int expires) { + return ""; + } } diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/impl/OssService.java b/zlt-business/file-center/src/main/java/com/central/file/service/impl/OssService.java new file mode 100644 index 00000000..e24ad421 --- /dev/null +++ b/zlt-business/file-center/src/main/java/com/central/file/service/impl/OssService.java @@ -0,0 +1,161 @@ +package com.central.file.service.impl; + +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.StrUtil; +import com.aliyun.oss.model.OSSObject; +import com.central.common.constant.CommonConstant; +import com.central.common.model.FileInfo; +import com.central.oss.model.ObjectInfo; +import com.central.oss.properties.FileServerProperties; +import com.central.oss.template.OssTemplate; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; + +/** + * @author lsl + * @date 2025/1/13 + *

+ */ +@Slf4j +@Service +@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_OSS) +public class OssService extends AbstractIFileService { + + private static final String PATH_SPLIT = "/"; + + @Resource + private OssTemplate ossTemplate; + + @Resource + private FileServerProperties fileServerProperties; + + @Override + protected String fileType() { + return FileServerProperties.TYPE_OSS; + } + + @Override + protected ObjectInfo uploadFile(MultipartFile file) { + return ossTemplate.upload(file); + } + + @Override + protected ObjectInfo uploadFile(String name, InputStream inputStream) throws IOException { + return ossTemplate.upload(name, inputStream,inputStream.available(),"image/jpeg"); + } + + @Override + protected void deleteFile(String objectPath) { + OSSObject ossObject = parsePath(objectPath); + ossTemplate.delete(ossObject.getBucketName(), ossObject.getKey()); + } + + @Override + public void out(String id, OutputStream os) { + FileInfo fileInfo = baseMapper.selectById(id); + if (fileInfo != null) { + OSSObject ossObject = parsePath(fileInfo.getPath()); + ossTemplate.out(ossObject.getBucketName(), ossObject.getKey(), os); + } + } + + @Override + public String getViewUrl(String fileId) { + FileInfo fileInfo = getFileInfo(fileId); + if (fileInfo != null) { + return ossTemplate.getViewUrl(fileInfo.getPath()); + } + return null; + } + + @Override + public String getViewUrlByPath(String path) { + + return ossTemplate.getViewUrl(path); + + } + + @Override + public String getZipViewUrlByPath(String path, String style) { + return ossTemplate.getViewUrl(path,style); + } + + @Override + public FileInfo getFileInfo(String id) { + if (StringUtils.isEmpty(id)) { + log.warn("文件ID为空"); + return null; + } + try { + log.info("开始查询文件信息: fileId={}", id); + FileInfo fileInfo = baseMapper.selectById(id.trim()); // 添加trim()去除可能的空格 + + if (fileInfo == null) { + log.warn("未找到文件信息: fileId={}", id); + return null; + } + + log.info("查询文件信息成功: fileId={}, path={}", fileInfo.getId(), fileInfo.getPath()); + return fileInfo; + } catch (Exception e) { + log.error("查询文件信息异常: fileId={}, error={}", id, e.getMessage(), e); + throw new RuntimeException("查询文件信息失败", e); + } + } + + @Override + public FileInfo createFile(String path) { + OSSObject ossObject = parsePath(path); + FileInfo fileInfo = new FileInfo(); + fileInfo.setPath(path); + fileInfo.setId(IdUtil.fastSimpleUUID()); + fileInfo.setName(ossObject.getKey()); + fileInfo.setSize(ossObject.getObjectMetadata().getContentLength()); + fileInfo.setUrl(fileServerProperties.getOss().getEndpoint() +PATH_SPLIT+ path); + fileInfo.setSource(fileType()); + fileInfo.setIsImg(ossObject.getKey().endsWith(".jpeg") || ossObject.getKey().endsWith(".png") || ossObject.getKey().endsWith(".gif")); + if (fileInfo.getIsImg()) { + fileInfo.setContentType("image/jpeg"); + }else { + fileInfo.setContentType("video/mp4"); + } + + int res = baseMapper.insert(fileInfo); + if (res > 0) { + return fileInfo; + } + return null; + } + + @Override + public List listFiles(String prefix) { + return ossTemplate.listFiles(fileServerProperties.getOss().getBucketName(), prefix); + } + + @Override + public String getViewUrlByPathAndExpires(String name, int expires) { + return ossTemplate.getViewUrl(name,expires); + } + + private OSSObject parsePath(String path) { + OSSObject ossObject = new OSSObject(); + if (StrUtil.isNotEmpty(path)) { + int splitIndex = path.lastIndexOf(CommonConstant.PATH_SPLIT); + if (splitIndex != -1) { + ossObject.setBucketName(path.substring(0, splitIndex)); + ossObject.setKey(path.substring(splitIndex + 1)); + } + } + return ossObject; + } + +} diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/impl/S3Service.java b/zlt-business/file-center/src/main/java/com/central/file/service/impl/S3Service.java index a6dd4b86..e7416074 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/service/impl/S3Service.java +++ b/zlt-business/file-center/src/main/java/com/central/file/service/impl/S3Service.java @@ -2,7 +2,7 @@ package com.central.file.service.impl; import cn.hutool.core.util.StrUtil; import com.central.common.constant.CommonConstant; -import com.central.file.model.FileInfo; +import com.central.common.model.FileInfo; import com.central.oss.model.ObjectInfo; import com.central.oss.properties.FileServerProperties; import com.central.oss.template.S3Template; @@ -13,7 +13,9 @@ import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; +import java.io.InputStream; import java.io.OutputStream; +import java.util.List; /** * @author zlt @@ -38,12 +40,27 @@ public class S3Service extends AbstractIFileService { return s3Template.upload(file); } + @Override + protected ObjectInfo uploadFile(String name, InputStream inputStream) { + return null; + } + @Override protected void deleteFile(String objectPath) { S3Object s3Object = parsePath(objectPath); s3Template.delete(s3Object.bucketName, s3Object.objectName); } + @Override + public String getViewUrlByPath(String name) { + return ""; + } + + @Override + public String getZipViewUrlByPath(String name, String style) { + return ""; + } + @Override public void out(String id, OutputStream os) { FileInfo fileInfo = baseMapper.selectById(id); @@ -53,6 +70,31 @@ public class S3Service extends AbstractIFileService { } } + @Override + public String getViewUrl(String id) { + return ""; + } + + @Override + public FileInfo getFileInfo(String id) { + return null; + } + + @Override + public FileInfo createFile(String path) { + return null; + } + + @Override + public List listFiles(String prefix) { + return List.of(); + } + + @Override + public String getViewUrlByPathAndExpires(String name, int expires) { + return ""; + } + @Setter @Getter private class S3Object { diff --git a/zlt-business/file-center/src/main/java/com/central/file/utils/FileUtil.java b/zlt-business/file-center/src/main/java/com/central/file/utils/FileUtil.java index f1da64e1..ca39f549 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/utils/FileUtil.java +++ b/zlt-business/file-center/src/main/java/com/central/file/utils/FileUtil.java @@ -1,16 +1,16 @@ package com.central.file.utils; +import cn.hutool.core.util.IdUtil; +import com.central.common.model.FileInfo; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.digest.DigestUtils; +import org.springframework.web.multipart.MultipartFile; + import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Date; -import cn.hutool.core.util.IdUtil; -import com.central.file.model.FileInfo; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.codec.digest.DigestUtils; -import org.springframework.web.multipart.MultipartFile; - /** * 文件工具类 * @@ -33,6 +33,16 @@ public class FileUtil { return fileInfo; } + public static FileInfo getFileInfo(String name, InputStream inputStream) { + FileInfo fileInfo = new FileInfo(); + fileInfo.setId(IdUtil.fastSimpleUUID()); + fileInfo.setName(name); + fileInfo.setContentType("image/jpeg"); + fileInfo.setIsImg(fileInfo.getContentType().startsWith("image/")); + fileInfo.setCreateTime(new Date()); + return fileInfo; + } + /** * 文件的md5 * diff --git a/zlt-business/file-center/src/main/java/com/central/file/utils/HexToJpeg.java b/zlt-business/file-center/src/main/java/com/central/file/utils/HexToJpeg.java new file mode 100644 index 00000000..6e1d4561 --- /dev/null +++ b/zlt-business/file-center/src/main/java/com/central/file/utils/HexToJpeg.java @@ -0,0 +1,39 @@ +package com.central.file.utils; + +import java.io.FileOutputStream; +import java.io.IOException; + + +public class HexToJpeg { + + public static void hexToBinary(String hexData, String outputFilePath) { + try (FileOutputStream fos = new FileOutputStream(outputFilePath)) { + byte[] binaryData = hexStringToByteArray(hexData); + fos.write(binaryData); + System.out.println("文件已保存至:" + outputFilePath); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static byte[] hexStringToByteArray(String hex) { + + // 检查字符串长度是否为偶数 + if (hex.length() % 2 != 0) { + throw new IllegalArgumentException("Invalid hex string length: " + hex.length()); + } + int len = hex.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + // 这里应该是安全的,因为我们已经检查了字符串长度是偶数 + data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + + Character.digit(hex.charAt(i + 1), 16)); + } + return data; + } + + + public static void main(String[] args) { + + } +} diff --git a/zlt-business/file-center/src/main/resources/application.yml b/zlt-business/file-center/src/main/resources/application.yml index d2099f0a..30d1ce89 100644 --- a/zlt-business/file-center/src/main/resources/application.yml +++ b/zlt-business/file-center/src/main/resources/application.yml @@ -1,6 +1,6 @@ spring: datasource: - url: jdbc:mysql://${zlt.datasource.ip}:3306/file_center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + url: jdbc:mysql://${zlt.datasource.ip}/file-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: ${zlt.datasource.username} password: ${zlt.datasource.password} driver-class-name: com.mysql.cj.jdbc.Driver @@ -8,7 +8,7 @@ spring: mybatis-plus: mapper-locations: classpath:/mapper/*Mapper.xml #实体扫描,多个package用逗号或者分号分隔 - typeAliasesPackage: com.central.file.model + typeAliasesPackage: com.central.common.model global-config: db-config: id-type: INPUT @@ -26,7 +26,7 @@ knife4j: zlt: file-server: - type: s3 + type: oss #fdfs: # web-url: ${zlt.fdfs.web-url} s3: @@ -34,12 +34,23 @@ zlt: accessKeySecret: ${zlt.s3.accessKeySecret} endpoint: ${zlt.s3.endpoint} bucketName: ${zlt.s3.bucketName} + cos: + secretId: ${zlt.cos.secretId} + secretKey: ${zlt.cos.secretKey} + endpoint: ${zlt.cos.endpoint} + region: ${zlt.cos.region} + bucketName: ${zlt.cos.bucketName} + oss: + secretId: ${zlt.oss.secretId} + secretKey: ${zlt.oss.secretKey} + endpoint: ${zlt.oss.endpoint} + bucketName: ${zlt.oss.bucketName} #多租户配置 tenant: - enable: true + enable: false #fastDFS配置 #fdfs: # soTimeout: 1500 # connectTimeout: 600 -# trackerList: ${zlt.fdfs.trackerList} \ No newline at end of file +# trackerList: ${zlt.fdfs.trackerList} diff --git a/zlt-business/file-center/src/main/resources/bootstrap.yml b/zlt-business/file-center/src/main/resources/bootstrap.yml index fd60207c..005bb0d4 100644 --- a/zlt-business/file-center/src/main/resources/bootstrap.yml +++ b/zlt-business/file-center/src/main/resources/bootstrap.yml @@ -3,4 +3,12 @@ server: spring: application: - name: file-center \ No newline at end of file + name: file-center + cloud: + nacos: + discovery: + ip: 119.45.169.13 + servlet: + multipart: + max-file-size: 20MB + max-request-size: 20MB diff --git a/zlt-business/file-center/src/main/resources/mapper/FileMapper.xml b/zlt-business/file-center/src/main/resources/mapper/FileMapper.xml index 63fbe3f6..fae1538c 100644 --- a/zlt-business/file-center/src/main/resources/mapper/FileMapper.xml +++ b/zlt-business/file-center/src/main/resources/mapper/FileMapper.xml @@ -20,9 +20,13 @@ - select * from file_info t - + order by t.create_time desc - \ No newline at end of file + + + diff --git a/zlt-business/order-center/README.md b/zlt-business/order-center/README.md new file mode 100644 index 00000000..3156812e --- /dev/null +++ b/zlt-business/order-center/README.md @@ -0,0 +1,45 @@ + +待开发功能: +1. 景区管理 +2. 套餐管理 +3. 素材管理 + + + +-- 订单创建时间 + 状态的联合索引(用于时间范围和状态统计) +CREATE INDEX idx_orders_create_status ON orders(create_time, order_status); + +-- 二维码ID + 创建时间的联合索引(用于按二维码统计) +CREATE INDEX idx_orders_qrcode_time ON orders(code_id, create_time); + +-- 景区ID + 创建时间的联合索引(用于按景区统计) +CREATE INDEX idx_orders_tourism_time ON orders(tourism_id, create_time); + +-- 设备编号 + 创建时间的联合索引(用于按设备统计) +CREATE INDEX idx_orders_device_time ON orders(device_sn, create_time); + +-- 软删除标记 + 创建时间的联合索引(用于过滤已删除订单) +CREATE INDEX idx_orders_del_time ON orders(is_del, create_time); + +服务号推送消息功能 + +1. 登录微信公众平台(mp.weixin.qq.com) + +2. 配置服务器: + - 进入"设置与开发 -> 基本配置" + - 填写服务器配置 + - URL: https://你的域名/wx/message + - Token: 与配置文件中的token一致 + - EncodingAESKey: 点击随机生成,复制到配置文件 + - 消息加解密方式: 选择安全模式 + +3. 配置消息模板: + - 进入"功能 -> 模板消息" + - 添加所需的消息模板 + - 复制模板ID到配置文件 + +4. 配置云托管(如果使用): + - 进入"云托管" + - 创建环境 + - 部署服务 + - 配置域名 diff --git a/zlt-business/order-center/pom.xml b/zlt-business/order-center/pom.xml new file mode 100644 index 00000000..118ee8a2 --- /dev/null +++ b/zlt-business/order-center/pom.xml @@ -0,0 +1,197 @@ + + + 4.0.0 + + com.zlt + zlt-business + 6.0.0 + + + order-center + 设备中心 + + + 17 + 17 + UTF-8 + + + + + + com.zlt + zlt-config + + + com.zlt + zlt-log-spring-boot-starter + + + com.zlt + zlt-common-spring-boot-starter + + + com.zlt + zlt-db-spring-boot-starter + + + com.zlt + zlt-redis-spring-boot-starter + + + com.zlt + zlt-loadbalancer-spring-boot-starter + + + com.zlt + zlt-sentinel-spring-boot-starter + + + + com.github.xiaoymin + knife4j-openapi3-jakarta-spring-boot-starter + + + com.zlt + search-client + + + + org.springframework.boot + spring-boot-starter-web + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.boot + spring-boot-starter-actuator + + + + mysql + mysql-connector-java + + + + io.micrometer + micrometer-registry-prometheus + + + junit + junit + test + + + org.hibernate + hibernate-validator + + + + + + + + javax.servlet + javax.servlet-api + 4.0.1 + compile + + + org.springframework + spring-webflux + + + + com.aliyun + alibabacloud-ice20201109 + 5.0.3 + + + + + org.springframework.retry + spring-retry + + + org.springframework.boot + spring-boot-starter-aop + + + com.zlt + zlt-wechat-spring-boot-starter + ${project.version} + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + com.spotify + docker-maven-plugin + + ${docker.image.prefix}/${project.artifactId} + + ${project.version} + latest + + true + ${docker.baseImage} + ${docker.volumes} + + ${docker.java.opts} + + ["sh","-c","java $JAVA_OPTS ${docker.java.security.egd} -jar /${project.build.finalName}.jar"] + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + ${project.artifactId} + + diff --git a/zlt-business/order-center/src/main/java/com/central/order/OrderCenterApp.java b/zlt-business/order-center/src/main/java/com/central/order/OrderCenterApp.java new file mode 100644 index 00000000..af3a7e09 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/OrderCenterApp.java @@ -0,0 +1,22 @@ +package com.central.order; + +import com.central.common.lb.annotation.EnableFeignInterceptor; +import com.central.search.annotation.EnableSearchClient; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * @author 作者 lsl E-mail: 1272745473@qq.com + */ +@EnableDiscoveryClient +@EnableSearchClient +@EnableTransactionManagement +@EnableFeignInterceptor +@SpringBootApplication +public class OrderCenterApp { + public static void main(String[] args) { + SpringApplication.run(OrderCenterApp.class, args); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/config/AliyunImsConfig.java b/zlt-business/order-center/src/main/java/com/central/order/config/AliyunImsConfig.java new file mode 100644 index 00000000..b7faf27c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/config/AliyunImsConfig.java @@ -0,0 +1,42 @@ +package com.central.order.config; + +import com.aliyun.auth.credentials.Credential; +import com.aliyun.auth.credentials.provider.StaticCredentialProvider; +import com.aliyun.sdk.service.ice20201109.AsyncClient; +import darabonba.core.client.ClientOverrideConfiguration; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "aliyun.ims") +public class AliyunImsConfig { + private String endpoint; // ice.cn-beijing.aliyuncs.com + private String ossEndpoint; // oss-cn-beijing.aliyuncs.com + private String accessKeyId; + private String accessKeySecret; + private String region; // cn-beijing + private String bucket; // goflyapp + private String callbackUrl; + + @Bean + public AsyncClient imsClient() { + // 配置凭证 + StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder() + .accessKeyId(accessKeyId) + .accessKeySecret(accessKeySecret) + .build()); + + // 配置客户端 + return AsyncClient.builder() + .region(region) + .credentialsProvider(provider) + .overrideConfiguration( + ClientOverrideConfiguration.create() + .setEndpointOverride(endpoint) + ) + .build(); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/config/AsyncConfig.java b/zlt-business/order-center/src/main/java/com/central/order/config/AsyncConfig.java new file mode 100644 index 00000000..b21b4534 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/config/AsyncConfig.java @@ -0,0 +1,31 @@ +package com.central.order.config; + +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +@Configuration +@EnableAsync +public class AsyncConfig implements AsyncConfigurer { + + @Override + public Executor getAsyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(5); + executor.setMaxPoolSize(10); + executor.setQueueCapacity(25); + executor.setThreadNamePrefix("message-async-"); + executor.initialize(); + return executor; + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return new SimpleAsyncUncaughtExceptionHandler(); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/config/ProfitSharingProperties.java b/zlt-business/order-center/src/main/java/com/central/order/config/ProfitSharingProperties.java new file mode 100644 index 00000000..0b6f75e9 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/config/ProfitSharingProperties.java @@ -0,0 +1,58 @@ +package com.central.order.config; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@ConfigurationProperties(prefix = "wechat.pay.profit-sharing") +@Component +public class ProfitSharingProperties { + /** + * 是否启用分账功能 + */ + @Builder.Default + private boolean enabled = true; + + /** + * 最大重试次数 + */ + @Builder.Default + private int maxRetryTimes = 3; + + /** + * 重试间隔(毫秒) + */ + @Builder.Default + private long retryInterval = 300000; // 5分钟 + + /** + * 平台分账比例(%) + */ + @Builder.Default + private String platformRate = "30"; + + /** + * 分账超时时间(毫秒) + */ + @Builder.Default + private long timeout = 1800000; // 30分钟 + + /** + * 是否启用异步处理 + */ + @Builder.Default + private boolean asyncEnabled = true; + + /** + * 异步处理线程池大小 + */ + @Builder.Default + private int asyncPoolSize = 5; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/constants/EditTaskStatus.java b/zlt-business/order-center/src/main/java/com/central/order/constants/EditTaskStatus.java new file mode 100644 index 00000000..afd51433 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/constants/EditTaskStatus.java @@ -0,0 +1,53 @@ +package com.central.order.constants; + +/** + * 编辑任务状态常量 + */ +public interface EditTaskStatus { + /** + * 待处理 + */ + int PENDING = 0; + + /** + * 处理中 + */ + int PROCESSING = 1; + + /** + * 处理完成 + */ + int COMPLETED = 2; + + /** + * 处理失败 + */ + int FAILED = 3; + + /** + * 判断是否为处理中状态 + */ + static boolean isProcessing(Integer status) { + return PROCESSING == status; + } + + /** + * 判断是否为完成状态 + */ + static boolean isCompleted(Integer status) { + return COMPLETED == status; + } + + /** + * 获取状态描述 + */ + static String getStatusDesc(Integer status) { + switch (status) { + case PENDING: return "待处理"; + case PROCESSING: return "处理中"; + case COMPLETED: return "已完成"; + case FAILED: return "失败"; + default: return "未知状态"; + } + } +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/constants/OrderStatusConstants.java b/zlt-business/order-center/src/main/java/com/central/order/constants/OrderStatusConstants.java new file mode 100644 index 00000000..f30536ee --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/constants/OrderStatusConstants.java @@ -0,0 +1,21 @@ +package com.central.order.constants; + +import com.central.order.enums.OrderStatus; + +public class OrderStatusConstants { + + // 已支付状态集合(已支付排队中、正在服务中、设备执行完成、素材上传中、素材上传完成) + public static final String PAID_STATUS = String.format("(%d,%d,%d,%d,%d)", + OrderStatus.PAID.getId(), // 1-已支付排队中 + OrderStatus.DOING.getId(), // 4-正在服务中 + OrderStatus.COMPLETE.getId(), // 3-设备执行完成 + OrderStatus.UPLOADING.getId(), // 5-素材上传中 + OrderStatus.UPLOADED.getId() // 6-素材上传完成 + ); + + // 退款状态集合(退款中、已退款) + public static final String REFUND_STATUS = String.format("(%d,%d)", + OrderStatus.REFUNDING.getId(), // 7-退款中 + OrderStatus.REFUNDED.getId() // 8-已退款 + ); +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/constants/ProfitSharingConstants.java b/zlt-business/order-center/src/main/java/com/central/order/constants/ProfitSharingConstants.java new file mode 100644 index 00000000..4eee7ccb --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/constants/ProfitSharingConstants.java @@ -0,0 +1,16 @@ +package com.central.order.constants; + +public interface ProfitSharingConstants { + String PROFIT_SHARING_PREFIX = "PS"; + String PROFIT_SHARING_DESC = "二维码分账"; + + int MAX_RETRY_TIMES = 3; + long RETRY_INTERVAL = 300000; // 5分钟 + + interface Status { + int INIT = 0; + int PROCESSING = 1; + int SUCCESS = 2; + int FAILED = 3; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/constants/WxConstants.java b/zlt-business/order-center/src/main/java/com/central/order/constants/WxConstants.java new file mode 100644 index 00000000..a9cd7e76 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/constants/WxConstants.java @@ -0,0 +1,35 @@ +package com.central.order.constants; + + +public class WxConstants { + /** + * Redis key前缀 + */ + public static final String REDIS_KEY_PREFIX = "wx:"; + + /** + * access_token相关 + */ + public static class AccessToken { + public static final String CACHE_KEY = REDIS_KEY_PREFIX + "access_token"; + public static final String LOCK_KEY = REDIS_KEY_PREFIX + "access_token:lock"; + public static final long EXPIRE_TIME = 7000; // 7000秒 + public static final long REFRESH_TIME = 5400000; // 1.5小时 + } + + /** + * 模板消息相关 + */ + public static class Template { + public static final String API_SEND = "https://api.weixin.qq.com/cgi-bin/message/template/send"; + public static final String API_GET_LIST = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template"; + public static final String API_DELETE = "https://api.weixin.qq.com/cgi-bin/template/del_private_template"; + } + + /** + * 微信接口相关 + */ + public static class Api { + public static final String ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/AutoCutVideoController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/AutoCutVideoController.java new file mode 100644 index 00000000..b6ed639d --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/AutoCutVideoController.java @@ -0,0 +1,266 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.model.SysUser; +import com.central.order.constants.EditTaskStatus; +import com.central.order.enums.OrderStatus; +import com.central.order.feign.UserCenterService; +import com.central.order.model.*; +import com.central.order.model.dto.CallbackDTO; +import com.central.order.model.params.EditTaskQueryParams; +import com.central.order.service.*; +import com.central.order.util.DateUtils; +import com.central.order.util.StringUtils; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 一键成片 + * + */ +@Slf4j +@RestController +@Tag(name = "剪辑管理") +@RequestMapping("/auto/cut") +@RequiredArgsConstructor +public class AutoCutVideoController { + + @Autowired + private IOrderService orderService; + @Autowired + private IEditTaskService editTaskService; + @Autowired + private IOrderFileService orderFileService; + @Autowired + private IVideoEditService videoEditService; + @Autowired + private IQrCodeService qrCodeService; + @Autowired + private WxMiniSubscribeService wxMiniSubscribeService; + + @Autowired + private UserCenterService userCenterService; + + @Autowired + private ITourismService tourismService; + + @Operation(summary = "根据订单号生成视频") + @PostMapping("/generate") + public Result generateVideo(@RequestParam String orderNo) { + try { + // 1. 验证订单状态 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null || !OrderStatus.isValidForEdit(order.getOrderStatus())) { + return Result.failed("订单状态不允许生成视频"); + } + + // 1. 检查是否开启一键成片 + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (!isVideoEditEnabled(qrCode)) { + log.info("未开启一键成片功能: orderNo={}, codeId={}", + order.getOrderNo(), order.getCodeId()); + return Result.failed("未开启一键成片功能"); + } + + // 2. 检查是否存在进行中的任务 + EditTask existingTask = editTaskService.getTaskByOrderSn(orderNo); + if (existingTask != null && EditTaskStatus.isProcessing(existingTask.getStatus())) { + return Result.failed("已存在进行中的编辑任务"); + } + + // 3. 创建新任务 + EditTask task = editTaskService.createTask(orderNo, order.getUserId()); + + // 4. 获取素材文件 + List orderFiles = orderFileService.getOrderFileByOrderNo(orderNo); + + // 5. 提交编辑任务 + String jobId = videoEditService.submitEditTask(orderNo, orderFiles); + + // 6. 更新任务信息 + task.setJobId(jobId); + task.setStatus(EditTaskStatus.PROCESSING); + editTaskService.saveOrUpdateTask(task); + + return Result.succeed(jobId); + + } catch (Exception e) { + log.error("提交视频编辑任务失败: orderNo={}", orderNo, e); + return Result.failed("提交任务失败:" + e.getMessage()); + } + } + + @Operation(summary = "智能剪辑回调接口") + @PostMapping("/callback") + public Result handleCallback(@RequestBody CallbackDTO callback) { + log.info("收到视频编辑回调: {}", callback); + try { + // 1. 验证回调信息 + if (!isValidCallback(callback)) { + return Result.failed("无效的回调信息"); + } + + // 2. 获取任务信息 + EditTask task = editTaskService.getTaskByJobId(callback.getJobId()); + if (task == null) { + return Result.failed("未找到对应的任务"); + } + + // 3. 处理成功回调 + if ("Success".equals(callback.getStatus())) { + // 更新任务状态 + editTaskService.updateTaskStatus( + callback.getJobId(), + EditTaskStatus.COMPLETED, + callback.getResult() + ); + + // 发送通知 + notifyUser(task.getUserId().toString(), task.getOrderSn()); + } + // 4. 处理失败回调 + else { + editTaskService.updateTaskStatus( + callback.getJobId(), + EditTaskStatus.FAILED, + callback.getErrorMessage() + ); + + // 记录错误日志 + log.error("视频编辑失败: jobId={}, error={}", + callback.getJobId(), callback.getErrorMessage()); + } + + return Result.succeed("回调处理成功"); + + } catch (Exception e) { + log.error("处理视频编辑回调失败", e); + return Result.failed("处理回调失败:" + e.getMessage()); + } + } + + @Operation(summary = "获取任务状态") + @GetMapping("/task/status/{orderNo}") + public Result getTaskStatus(@PathVariable String orderNo) { + try { + EditTask task = editTaskService.getTaskByOrderSn(orderNo); + if (task == null) { + return Result.failed("未找到任务记录"); + } + return Result.succeed(task); + } catch (Exception e) { + log.error("获取任务状态失败", e); + return Result.failed("获取任务状态失败:" + e.getMessage()); + } + } + + + private boolean isValidCallback(CallbackDTO callback) { + // Implementation of isValidCallback method + return false; // Placeholder return, actual implementation needed + } + + private void notifyUser(String userId,String orderNo) { + try { + // 1. 获取用户信息 + SysUser user = userCenterService.findUserById(Long.valueOf(userId)); + if (user == null || user.getOpenId() == null) { + log.warn("未找到用户或用户未绑定小程序openId,无法发送成片完成通知: userId={}", userId); + return; + } + + // 2. 获取任务和订单信息 + // 假设 message 里包含订单号或任务名,实际可根据 EditTask 查找 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null) { + log.warn("未找到订单信息,无法发送成片完成通知: orderNo={}", orderNo); + return; + } + + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + String result = "视频已生成请查阅"; + + wxMiniSubscribeService.sendPaySuccessMsg( + user.getOpenId(), + tourism.getTourismName(), + orderNo, + result, + StringUtils.fenToYuan(order.getOrderAmount()), + DateUtils.sdf.format(order.getPayTime()) + ); + log.info("已发送一键成片完成通知: userId={}, openId={}, orderNo={}", userId, user.getOpenId(), orderNo); + } catch (Exception e) { + log.error("发送一键成片完成通知失败: userId={}, message={}", userId, orderNo, e); + } + } + + + @Operation(summary = "获取剪辑任务列表") + @GetMapping("/list") + public Result> getTaskList( + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer limit, + @RequestParam(required = false) String orderSn, + @RequestParam(required = false) String jobId, + @RequestParam(required = false) Integer status) { + try { + EditTaskQueryParams params = EditTaskQueryParams.builder() + .page(page) + .limit(limit) + .orderSn(orderSn) + .jobId(jobId) + .status(status) + .build(); + + PageResult result = editTaskService.getTaskList(params); + return Result.succeed(result); + + } catch (Exception e) { + log.error("查询剪辑任务列表失败", e); + return Result.failed("查询任务列表失败"); + } + } + + @Operation(summary = "保存或更新剪辑任务") + @PostMapping("/save") + public Result saveOrUpdateTask(@RequestBody EditTask task) { + try { + boolean success = editTaskService.saveOrUpdateTask(task); + return Result.succeed(success); + + } catch (Exception e) { + log.error("保存剪辑任务失败: task={}", task, e); + return Result.failed("保存任务失败: " + e.getMessage()); + } + } + + @Operation(summary = "删除剪辑任务") + @DeleteMapping("/delete/{id}") + public Result deleteTask(@PathVariable Integer id) { + try { + boolean success = editTaskService.deleteTask(id); + return Result.succeed(success); + + } catch (Exception e) { + log.error("删除剪辑任务失败: id={}", id, e); + return Result.failed("删除任务失败: " + e.getMessage()); + } + } + + /** + * 检查是否开启一键成片功能 + */ + private boolean isVideoEditEnabled(QrCode qrCode) { + return qrCode != null + && qrCode.getEnableVideoEdit() != null + && qrCode.getEnableVideoEdit() == 1 + && qrCode.getTemplateId() != null; // 确保有模板ID + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/DashboardController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/DashboardController.java new file mode 100644 index 00000000..600e4a66 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/DashboardController.java @@ -0,0 +1,34 @@ +package com.central.order.controller; + +import com.central.common.model.Result; +import com.central.order.model.vo.DashboardStatisticsVO; +import com.central.order.service.IDashboardService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RestController +@RequestMapping("/dashboard") +@Tag(name = "首页统计", description = "首页统计数据接口") +@RequiredArgsConstructor +public class DashboardController { + + private final IDashboardService dashboardService; + + @Operation(summary = "获取首页统计数据") + @GetMapping("/statistics") + public Result getStatistics() { + try { + DashboardStatisticsVO statistics = dashboardService.getDashboardStatistics(); + return Result.succeed(statistics, "获取首页统计数据成功"); + } catch (Exception e) { + log.error("获取首页统计数据失败", e); + return Result.failed("获取统计数据失败:" + e.getMessage()); + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/HomeCarouselController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/HomeCarouselController.java new file mode 100644 index 00000000..34194594 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/HomeCarouselController.java @@ -0,0 +1,90 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.feign.FileCenterService; +import com.central.order.model.HomeCarousel; +import com.central.order.service.IHomeCarouselService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +/** + * HomeCarousel information + * + * @author lsl + * @date 2025-2-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "HomeCarousel管理") +@RequestMapping("/home/carousel") +@RequiredArgsConstructor +public class HomeCarouselController { + + @Autowired + private IHomeCarouselService homeCarouselService; + + @Autowired + private FileCenterService fileCenterService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + PageResult pageResult = homeCarouselService.findList(params); + if (pageResult.getCount()>0){ + for (HomeCarousel homeCarousel: pageResult.getData()){ + homeCarousel.setImageUrl(fileCenterService.getViewUrlByPath(homeCarousel.getImageUrl())); + } + } + return pageResult; + } + + @GetMapping("/app") + public Result> homeList() { + List list = homeCarouselService.list(); + if (!list.isEmpty()){ + for (HomeCarousel homeCarousel: list){ + homeCarousel.setImageUrl(fileCenterService.getViewUrlByPath(homeCarousel.getImageUrl())); + } + } + return Result.succeed(list,"获取成功"); + } + + @PostMapping() + public Result saveOrUpdate(@RequestBody HomeCarousel homeCarousel) { + return homeCarouselService.saveOrUpdateHomeCarousel(homeCarousel); + } + + @Operation(summary = "查询HomeCarousel") + @GetMapping("/{id}") + public Result getHomeCarousel(@PathVariable("id") Long id) { + HomeCarousel homeCarousel = homeCarouselService.getById(id); + if (homeCarousel == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(homeCarousel,"获取成功"); + } + + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + homeCarouselService.removeById(id); + return Result.succeed("操作成功"); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/MessageController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/MessageController.java new file mode 100644 index 00000000..c3baaea8 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/MessageController.java @@ -0,0 +1,47 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.Message; +import com.central.order.service.IMessageService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/messages") +@Tag(name = "站内信管理") +@RequiredArgsConstructor +public class MessageController { + + private final IMessageService messageService; + + @Operation(summary = "获取消息列表") + @GetMapping + public PageResult getMessages(@RequestParam Map params) { + return messageService.findMessages(params); + } + + @Operation(summary = "标记消息已读") + @PutMapping("/{id}/read") + public Result markAsRead(@PathVariable Long id) { + return messageService.markAsRead(id); + } + + @Operation(summary = "标记所有消息已读") + @PutMapping("/read/all") + public Result markAllAsRead() { + return messageService.markAllAsRead(); + } + + @Operation(summary = "删除消息") + @DeleteMapping("/{id}") + public Result deleteMessage(@PathVariable Long id) { + return messageService.deleteMessage(id); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java new file mode 100644 index 00000000..82c11ba0 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java @@ -0,0 +1,683 @@ +package com.central.order.controller; + +import com.alibaba.csp.sentinel.util.StringUtil; +import com.central.common.constant.CommonConstant; +import com.central.common.context.LoginUserContextHolder; +import com.central.common.context.TenantContextHolder; +import com.central.common.model.LoginAppUser; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.model.SysUser; +import com.central.log.annotation.AuditLog; +import com.central.order.enums.CommonStatus; +import com.central.order.enums.OrderStatus; +import com.central.order.feign.DeviceCenterService; +import com.central.order.feign.FileCenterService; +import com.central.order.feign.UserCenterService; +import com.central.order.model.*; +import com.central.order.service.*; +import com.central.wechat.config.WxPayConfigFactory; +import com.central.wechat.entity.WechatConfig; +import com.central.wechat.feign.WechatConfigService; +import com.wechat.pay.java.service.payments.jsapi.model.*; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.*; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "订单管理") +@RequiredArgsConstructor +public class OrderController { + + //设备执行任务默认时间长度3分钟 + private static final long DEVICE_EXEC_TIME = 4; + + @Autowired + private IOrderService orderService; + + @Autowired + private IOrderFileService orderFileService; + + @Autowired + private ITourismService tourismService; + + @Autowired + private ITourismFileService tourismFileService; + + @Autowired + private UserCenterService userCenterService; + + @Autowired + private FileCenterService fileCenterService; + + @Autowired + private IQrCodeService qrCodeService; + + @Autowired + private WechatConfigService wechatConfigService; + + @Value("${file.oss-url}") + private String cdnOssUrl; + + @Value("${file.cdn-url}") + private String cdnUrl; + + @Value("${file.style}") + private String fileStyle; + // 获取当前日期,格式化为 yyyyMMdd + SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.DATEMINUTE_FORMAT); + + @Autowired + private DeviceCenterService deviceCenterService; + + @Autowired + private IProfitSharingService profitSharingService; + + @Autowired + private WxPayConfigFactory wxPayConfigFactory; + + /** + * 列表 + */ + @Operation(summary = "查询全部列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping("/list") + public PageResult list(@RequestParam Map params) { + return orderService.findList(params); + } + + /** + * 列表 + */ + @Operation(summary = "查询用户订单列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult listByUser(@RequestParam Map params) { + LoginAppUser user = LoginUserContextHolder.getUser(); + if (user == null) { + return new PageResult<>(); + } + params.put("userId", user.getId()); + return orderService.findListByUser(params); + } + + /** + * 列表 + */ + @Operation(summary = "查询用户订单详情列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping("/user") + public PageResult listInfoByUser(@RequestParam Map params) { + LoginAppUser user = LoginUserContextHolder.getUser(); + params.put("userId", user.getId()); + String fileType = MapUtils.getString(params, "fileType"); + if (StringUtil.isBlank(fileType)) { + fileType = "image/jpeg"; + } + + PageResult result = orderService.findListByUser(params); + if (result.getCount() > 0){ + List page = new ArrayList<>(); + Map fileMap = new HashMap<>(); + fileMap.put("style", fileStyle); + for(Order order : result.getData()){ + Map orderFileMap = new HashMap<>(); + orderFileMap.put("time", sdf.format(order.getCreateTime())); + orderFileMap.put("addr", tourismService.getTourismById(order.getTourismId()).getTourismAddress()); + orderFileMap.put("orderNo", order.getOrderNo()); + + List list = orderFileService.getOrderFileByOrderNoAndFileType(order.getOrderNo(),fileType); + List> resultList = new ArrayList<>(); + if (!list.isEmpty()){ + for (OrderFile orderFile : list){ + Map imgMap = new HashMap<>(); + String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath()); + imgMap.put("url", url.replace(cdnOssUrl,cdnUrl)); + imgMap.put("contentType", orderFile.getFileType()); + fileMap.put("path",orderFile.getFilePath()); + imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap)); + resultList.add(imgMap); + } + } + orderFileMap.put("imgList", resultList); + page.add(orderFileMap); + } + return PageResult.builder().data(page).resp_code(0).count(result.getCount()).build(); + } + return new PageResult<>(); + } + + + // 创建订单--》 + // 返回前端订单信息--》 + // 前端发起支付(PUT api-order/{id}/pay)--》 + // 等待回调更新订单状态(微信支付回调接口/api-order/pay/notify)--》 + // 同时创建支付记录(/api-order/payment) + // 前端进入排队队列中(/api-order/queue)已支付订单列表 + // 设备执行完成后更新订单状态已完成(根据设备上报状态触发或者设备直接调用接口进行更新任务状态) + @Operation(summary = "创建订单") + @PostMapping + public Result createOrder(@RequestBody Order order) { + + LoginAppUser user = LoginUserContextHolder.getUser(); + + order.setUserId(user.getId()); + order.setTenantId(TenantContextHolder.getTenant()); + + List userOrderList = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId(),OrderStatus.UNPAID.getId()); + if (!userOrderList.isEmpty()){ + return Result.succeed("已存在订单,请前往订单页确认,请勿重复下单"); + } + + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (qrCode != null){ + if (qrCode.getStatus().equals(CommonStatus.UNABLE.getId())){ + return Result.failed("该二维码已过期"); + } + //设置订单所属tenantId + TenantContextHolder.setTenant(qrCode.getTenantId()); + order.setTourismId(qrCode.getTourismId()); + order.setDeviceSn(qrCode.getDeviceSn()); + order.setOrderAmount(qrCode.getPrice()); + }else { + Assert.notNull(qrCode,"二维码不存在"); + } + boolean result = orderService.createOrder(order); + if (result) { + return Result.succeed(order,"订单创建成功"); + } else { + return Result.succeed("订单已创建"); + } + } + + + /** + * 公众号小程序支付 + * + * @param orderId 微信公众号对应微信付款用户的唯一标识 + * @return 返回jsapi所需参数 + */ + + @Operation(summary = "生成预支付订单") + @PutMapping("/{orderId}/pay") + public Result payOrder(@PathVariable("orderId") Long orderId) { + try { + // 1. 获取用户和订单信息 + SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId()); + Order order = orderService.getById(orderId); + if (order == null) { + return Result.failed("订单数据不存在"); + } + + // 检查是否需要开启分账 + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (qrCode == null) { + return Result.failed("二维码不存在"); + } + + // 3. 创建支付请求 + PrepayRequest request = new PrepayRequest(); + WechatConfig wechatConfig = wechatConfigService.getConfig("PAY",qrCode.getTenantId()); + + // 设置基本支付信息 + Amount amount = new Amount(); + amount.setTotal(Integer.parseInt(order.getOrderAmount())); + request.setAmount(amount); + request.setAppid(wechatConfig.getAppId()); + request.setMchid(wechatConfig.getMerchantId()); + request.setDescription(order.getOrderNo()); + request.setNotifyUrl(wechatConfig.getNotifyUrl()); + request.setOutTradeNo(order.getOrderNo()); + + // 设置支付者信息 + Payer payer = new Payer(); + payer.setOpenid(user.getOpenId()); + request.setPayer(payer); + + // 设置分账信息 + SettleInfo settleInfo = new SettleInfo(); + if (isEnableProfit(qrCode)) { + settleInfo.setProfitSharing(true); + request.setSettleInfo(settleInfo); + + // 创建分账记录 + ProfitSharing profitSharing = profitSharingService.createProfitSharing(order,qrCode); + } else { + settleInfo.setProfitSharing(false); + request.setSettleInfo(settleInfo); + } + + // 5. 调用支付接口 + PrepayWithRequestPaymentResponse response = wxPayConfigFactory.createJsapiService(qrCode.getTenantId()).prepayWithRequestPayment(request); + + // 6. 返回结果 + return Result.succeed(response, order.getOrderNo()); + } catch (Exception e) { + log.error("创建预支付订单失败", e); + return Result.failed("创建预支付订单失败:" + e.getMessage()); + } + } + + /** + * 检查是否开启分润 + */ + private boolean isEnableProfit(QrCode qrCode) { + return qrCode != null && + Integer.valueOf(1).equals(qrCode.getEnableProfit()) && + qrCode.getPayeeStatus() != null && + qrCode.getPayeeStatus() == 1 && // 确保分账账号已验证 + qrCode.getPayeeAccount() != null && // 确保有收款账号 + qrCode.getProfitRate() != null; // 确保有分润比例 + } + + @Operation(summary = "获取排队总览信息") + @GetMapping("/queue/info") + public Result getQueueInfo(@RequestParam String codeId) { + LoginAppUser user = LoginUserContextHolder.getUser(); + QrCode qrCode = qrCodeService.getByCodeId(codeId); + Assert.notNull(qrCode,"二维码CODEID不能为空"); + Order order = orderService.getOrderByStatusAndUser(OrderStatus.PAID.getId(), user.getId(),qrCode.getTourismId()); + Map map = new HashMap<>(); + map.put("price",appendPriceStr(qrCode.getPrice())); + //如果用户存在已支付订单,则查询当前排在第几 + if (order != null){ + Integer count = orderService.getOrderRankingByOrderId(order.getId(),qrCode.getTourismId()); + map.put("count", count == 1 ? -1 : count-1 ); + map.put("time",Math.multiplyExact((count-1),DEVICE_EXEC_TIME)); + }else { + Long count = orderService.getOrderCountByStatus(OrderStatus.PAID.getId(),qrCode.getTourismId()); + map.put("count", count == 0 ? -1 : count); + map.put("time",Math.multiplyExact(count,DEVICE_EXEC_TIME)); + } + return Result.succeed(map,"获取成功"); + } + + @Operation(summary = "获取订单排队总览信息") + @GetMapping("/queue/info/{orderNo}") + public Result getQueueInfoByOrderNo(@PathVariable("orderNo") String orderNo) { + + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不能为空"); + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + Map map = new HashMap<>(); + map.put("price",appendPriceStr(qrCode.getPrice())); + Integer count = orderService.getOrderRankingByOrderId(order.getId(),qrCode.getTourismId()); + map.put("count", count == 1 ? -1 : count-1 ); + map.put("time",Math.multiplyExact((count-1),DEVICE_EXEC_TIME)); + return Result.succeed(map,"获取成功"); + } + + @Operation(summary = "获取用户是否存在排队订单") + @GetMapping("/queue/info/user") + public Result getOrderInfoByUser() { + LoginAppUser user = LoginUserContextHolder.getUser(); + Map res = new HashMap(); + List orders = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId(),OrderStatus.DOING.getId()); + if(!orders.isEmpty()){ + for (Order order : orders){ + order.setCreatedTime(sdf.format(order.getCreateTime())); + if(order.getOrderStatus().equals(OrderStatus.PAID.getId())){ + res.put("orderNo",order.getOrderNo()); + Integer count = orderService.getOrderRankingByOrderId(order.getId(),order.getTourismId()); + res.put("orderStatus",order.getOrderStatus()); + res.put("waitCount", count == 1 ? -1 : count-1 ); + res.put("waitTime",Math.multiplyExact((count-1),DEVICE_EXEC_TIME)); + res.put("createdTime",sdf.format(order.getCreateTime())); + } + if (order.getOrderStatus().equals(OrderStatus.DOING.getId())){ + res.put("orderNo",order.getOrderNo()); + res.put("createdTime",sdf.format(order.getCreateTime())); + res.put("orderStatus",order.getOrderStatus()); + } + } + } + return Result.succeed(res,"获取成功"); + + } + + @Operation(summary = "获取排队中的订单列表") + @GetMapping("/queue") + public Result> getOrdersInQueue() { + List orders = orderService.getOrdersInQueue(); + return Result.succeed(orders,"获取成功"); + } + + // 获取排队中的订单列表 + @Operation(summary = "获取排队中的第一个订单") + @GetMapping("/queue/first") + public Result getOrdersInQueueFirstOne(@RequestParam String deviceSn) { + Assert.notNull(deviceSn,"设备SN不能为空"); + if (orderService.getUnCompleteOrderCount(deviceSn)==0){ + List orders = orderService.getOrdersInQueueByDevice(deviceSn); + if (!orders.isEmpty()){ + Order order = orders.get(0); + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + Assert.notNull(qrCode,"二维码数据不能为空"); + + // 从二维码中获取航线ID + String waylineId = qrCode.getWaylineId(); + // 根据航线ID获取对应的文件路径 + String waylineFilePath = fileCenterService.getFileViewUrl(waylineId); + Assert.notNull(waylineFilePath,"订单航线数据不能为空"); + + order.setFileMd5(deviceCenterService.getLineFileSign(waylineId)); + order.setWaylineLinkUrl(waylineFilePath); + order.setStreamUrls(deviceCenterService.getStreamUrls(order.getDeviceSn())); + return Result.succeed(order,"获取成功"); + } + } + return Result.failed("未存在排队队列"); + } + + // 处理排队中的订单(模拟消费通知等操作) + @Operation(summary = "通知排队中的订单") + @PutMapping("/queue/process") + public Result processOrdersInQueue() { + orderService.processOrdersInQueue(); + return Result.succeed("排队订单处理已启动"); + } + + @Operation(summary = "更新订单正在服务中状态") + @AuditLog(operation = "'下发任务更新订单正在服务中状态:' + #orderNo") + @PostMapping("/status") + public Result updateOrderStatusDoing(@RequestBody String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order, "订单数据不能为空"); + if (order.getOrderStatus().equals(OrderStatus.PAID.getId())) { + order.setOrderStatus(OrderStatus.DOING.getId()); + if (orderService.updateOrder(order)) { // 这里会触发事件 + return Result.succeed("更新成功"); + } + } + return Result.failed("未查询到订单数据"); + } + + @Operation(summary = "根据设备状态更新订单正在服务中状态") + @AuditLog(operation = "'下发任务更新订单正在服务中状态:' + #orderNo") + @PutMapping("/device/status") + public Result updateOrderStatusDoingFromDevice(@RequestBody Map payload) { + Order order = orderService.getOrderByNumber(payload.get("orderNo").toString()); + Assert.notNull(order,"订单数据不能为空"); + if (order.getOrderStatus().equals(OrderStatus.PAID.getId())){ + order.setOrderStatus(OrderStatus.DOING.getId()); + if (orderService.updateOrder(order)){ + return Result.succeed("更新成功"); + } + } + return Result.failed("未查询到订单数据"); + } + + @Operation(summary = "机库更新订单完成状态") + @AuditLog(operation = "'机库更新订单完成状态:' + #payload") + @PutMapping("/update") + public Result updateOrderStatusCompleted(@RequestBody Map payload) { + Order order = orderService.getOrderByNumber(payload.get("orderNo").toString()); + Assert.notNull(order,"订单数据不能为空"); + if (order.getOrderStatus().equals(OrderStatus.DOING.getId()) + || order.getOrderStatus().equals(OrderStatus.UPLOADED.getId()) + || order.getOrderStatus().equals(OrderStatus.UPLOADING.getId())){ + order.setOrderStatus(OrderStatus.COMPLETE.getId()); + if (orderService.updateOrder(order)){ + return Result.succeed("更新成功"); + } + }else { + return Result.failed("已更新"); + } + return Result.failed("未查询到订单数据"); + } + + @Operation(summary = "取消订单") + @PutMapping("/{id}") + public Result cancelOrder(@PathVariable("id") Long id) { + Order order = orderService.getById(id); + order.setOrderStatus(OrderStatus.CANCELED.getId()); + boolean res = orderService.updateOrder(order); // 这里会触发事件 + if (res) { + return Result.succeed("已取消"); + } + return Result.failed("请重试"); + } + + @Operation(summary = "后台管理更新订单") + @PostMapping("/update/order") + public Result updateOrder(@RequestBody Order order) { + LoginAppUser loginAppUser = LoginUserContextHolder.getUser(); + // + if (loginAppUser.getId() == 1 || loginAppUser.getId() == 1073) { + boolean res = orderService.updateOrder(order); + if (res){ + return Result.succeed("已更新"); + } + } + + return Result.failed("请重试"); + } + + @Operation(summary = "机库查询订单执行情况") + @AuditLog(operation = "'机库查询订单执行情况:' + #orderNo") + @GetMapping("/status/{orderNo}") + public Result getOrderExecStatus(@PathVariable("orderNo") String orderNo) { + + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据为空"); + if (order.getOrderStatus().equals(OrderStatus.COMPLETE.getId())){ + return Result.failed("已执行"); + }else if (order.getOrderStatus().equals(OrderStatus.PAID.getId())){ + return Result.succeed("待执行"); + } + return Result.failed("不满足执行条件"); + } + + @Operation(summary = "获取订单对应的景区素材") + @GetMapping("/resource/tourism/{orderNo}") + public Result> getTourismByOrder(@PathVariable("orderNo") String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不存在"); + List tourismFiles = tourismFileService.getByTourismId(order.getTourismId()); + if (!tourismFiles.isEmpty()){ + for (TourismFile tourismFile : tourismFiles){ + tourismFile.setImageUrl(fileCenterService.getViewUrlByPath(tourismFile.getImageUrl())); + } + } + return Result.succeed(tourismFiles,"获取成功"); + } + + @Operation(summary = "获取订单对应的景区Info") + @GetMapping("/info/tourism/{orderNo}") + public Result getTourismInfoByOrder(@PathVariable("orderNo") String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不存在"); + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + return Result.succeed(tourism,"获取成功"); + } + + @Operation(summary = "获取订单的设备") + @GetMapping("/device/{orderNo}") + public Result getDeviceByOrder(@PathVariable("orderNo") String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不存在"); + return Result.succeed(order.getDeviceSn(),"获取成功"); + } + + @Operation(summary = "获取订单状态") + @GetMapping("/{orderNo}/status") + public String getOrderStatusByOrderNo(@PathVariable("orderNo") String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不存在"); + return order.getOrderStatus().toString(); + } + + @Operation(summary = "获取订单详情") + @GetMapping("/detail/{orderNo}") + public Result> getOrderDetail(@PathVariable("orderNo") String orderNo) { + try { + // 获取订单基本信息 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null) { + return Result.failed("订单不存在"); + } + + // 获取景区信息 + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + if (tourism == null) { + return Result.failed("景区信息不存在"); + } + + // 获取订单文件信息 + List orderFiles = orderFileService.getOrderFileByOrderNo(orderNo); + + // 构建返回数据 + Map detailMap = new HashMap<>(); + // 订单基本信息 + detailMap.put("orderNo", order.getOrderNo()); + detailMap.put("orderStatus", order.getOrderStatus()); + detailMap.put("orderAmount", appendPriceStr(order.getOrderAmount())); + detailMap.put("createTime", sdf.format(order.getCreateTime())); + detailMap.put("deviceSn", order.getDeviceSn()); + detailMap.put("mobile", userCenterService.findUserById(order.getUserId()).getMobile()); + + // 景区信息 + Map tourismMap = new HashMap<>(); + tourismMap.put("tourismName", tourism.getTourismName()); + tourismMap.put("tourismAddress", tourism.getTourismAddress()); + tourismMap.put("tourismDesc", tourism.getTourismDesc()); + detailMap.put("tourism", tourismMap); + + // 订单文件信息 + if (!orderFiles.isEmpty()) { + List> fileList = new ArrayList<>(); + Map fileMap = new HashMap<>(); + fileMap.put("style", fileStyle); + + for (OrderFile orderFile : orderFiles) { + Map fileInfo = new HashMap<>(); + String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath()); + fileInfo.put("url", url.replace(cdnOssUrl, cdnUrl)); + fileInfo.put("contentType", orderFile.getFileType()); + fileMap.put("path", orderFile.getFilePath()); + fileInfo.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap)); + fileList.add(fileInfo); + } + detailMap.put("files", fileList); + } + + // 如果是排队中的订单,添加排队信息 + if (OrderStatus.PAID.getId().equals(order.getOrderStatus())) { + Integer ranking = orderService.getOrderRankingByOrderId(order.getId(), order.getTourismId()); + detailMap.put("queueCount", ranking == 1 ? -1 : ranking - 1); + detailMap.put("estimatedTime", Math.multiplyExact((ranking - 1), DEVICE_EXEC_TIME)); + } + + return Result.succeed(detailMap, "获取成功"); + + } catch (Exception e) { + log.error("获取订单详情失败: orderNo={}", orderNo, e); + return Result.failed("获取订单详情失败"); + } + } + + /** + * 将分的价格转换为元的str,方便前端显示 + * @param str + * @return + */ + private String appendPriceStr(String str){ + // 获取字符串长度 + int length = str.length(); + + // 获取除了最后两位字符之外的部分 + String prefix = str.substring(0, length - 2); + + // 获取最后两位字符 + String lastTwo = str.substring(length - 2); + + // 在最后两位字符前添加小数点 + return prefix + "." + lastTwo; + } + + /** + * 列表 + */ + @Operation(summary = "查询用户订单临时演示") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping("/user/temp") + public PageResult listInfoByUserForTemp(@RequestParam Map params) { + params.put("orderNo", "332025051700001"); + String fileType = MapUtils.getString(params, "fileType"); + if (StringUtil.isBlank(fileType)) { + fileType = "image/jpeg"; + } + + PageResult result = orderService.findList(params); + if (result.getCount() > 0){ + List page = new ArrayList<>(); + Map fileMap = new HashMap<>(); + fileMap.put("style", fileStyle); + for(Order order : result.getData()){ + Map orderFileMap = new HashMap<>(); + orderFileMap.put("time", sdf.format(order.getCreateTime())); + orderFileMap.put("addr", tourismService.getTourismById(order.getTourismId()).getTourismAddress()); + orderFileMap.put("orderNo", order.getOrderNo()); + +// List list = orderFileService.getOrderFileByOrderNoAndFileType(order.getOrderNo(),fileType); + List list = fileCenterService.getListFiles("temp/332025051700001/Remote-Control/"); + List> resultList = new ArrayList<>(); + if (!list.isEmpty()){ + list.remove(0); + for (String orderFile : list){ + Map imgMap = new HashMap<>(); + String url = fileCenterService.getViewUrlByPath(orderFile); + imgMap.put("url", url.replace(cdnOssUrl,cdnUrl)); + if (orderFile.endsWith(".jpeg") || orderFile.endsWith(".png")){ + imgMap.put("contentType", "image/jpeg"); + } + if (orderFile.endsWith(".mp4")){ + imgMap.put("contentType", "video/mp4"); + } + fileMap.put("path",orderFile); + imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap)); + resultList.add(imgMap); + } + } + orderFileMap.put("imgList", resultList); + page.add(orderFileMap); + } + return PageResult.builder().data(page).resp_code(0).count(result.getCount()).build(); + } + return new PageResult<>(); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderFileController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderFileController.java new file mode 100644 index 00000000..34abbe78 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderFileController.java @@ -0,0 +1,187 @@ +package com.central.order.controller; + +import com.central.common.context.LoginUserContextHolder; +import com.central.common.model.FileInfo; +import com.central.common.model.LoginAppUser; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.enums.OrderStatus; +import com.central.order.feign.FileCenterService; +import com.central.order.model.Order; +import com.central.order.model.OrderFile; +import com.central.order.service.IOrderFileService; +import com.central.order.service.IOrderService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.CollectionUtils; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Order Files information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "任务资源管理") +@RequestMapping("/files") +@RequiredArgsConstructor +public class OrderFileController { + + @Autowired + private IOrderFileService orderFileService; + + @Autowired + private FileCenterService fileCenterService; + + @Autowired + private IOrderService orderService; + + @Value("${file.style}") + private String fileStyle; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + PageResult pageResult = orderFileService.findList(params); + Map fileMap = new HashMap<>(); + fileMap.put("style", fileStyle); + if (pageResult.getResp_code() == 0){ + for (OrderFile orderFile: pageResult.getData()){ + orderFile.setViewUrl(fileCenterService.getViewUrlByPath(orderFile.getFilePath())); + fileMap.put("path", orderFile.getFilePath()); + orderFile.setZipViewUrl(fileCenterService.getViewUrlByPathStyle(fileMap)); + } + } + return pageResult; + } + + /** + * 列表 + */ + @Operation(summary = "查询用户列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping("/user") + public PageResult listByUser(@RequestParam Map params) { + LoginAppUser user = LoginUserContextHolder.getUser(); + params.put("userId", user.getId()); + return orderFileService.findListByUser(params); + } + + @Operation(summary = "创建订单资源") + @PostMapping + public Result createOrderFile(@RequestBody OrderFile orderFile) { + + LoginAppUser user = LoginUserContextHolder.getUser(); + orderFile.setFileType(fileCenterService.getFileContentType(orderFile.getFileId())); + orderFile.setUserId(user.getId()); + boolean result = orderFileService.createOrderFile(orderFile); + if (result) { + return Result.succeed(orderFile,"文件资源创建成功"); + } else { + return Result.failed("文件资源创建失败"); + } + } + + public Result getOrderFile(@PathVariable("fileId") String fileId) { + OrderFile orderFile = orderFileService.getOrderFileByFileId(fileId); + if (orderFile == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(orderFile,"获取成功"); + } + + @Operation(summary = "查询订单资源列表") + @GetMapping("/order/{orderNo}") + public Result> getOrderFiles(@PathVariable("orderNo") String orderNo) { + List orderFiles = orderFileService.getOrderFileByOrderNo(orderNo); + if (!CollectionUtils.isEmpty(orderFiles)) { + for (OrderFile orderFile : orderFiles) { + String viewUrl = fileCenterService.getFileViewUrl(orderFile.getFileId()); + orderFile.setViewUrl(viewUrl); + } + }else { + return Result.failed("暂无数据"); + } + return Result.succeed(orderFiles); + } + + @Operation(summary = "查询用户订单资源列表") + @GetMapping("/user/{userId}") + public Result> getUserOrderFiles(@PathVariable("userId") Long userId) { + List orderFiles = orderFileService.getOrderFileByUserId(userId); + if (!CollectionUtils.isEmpty(orderFiles)) { + for (OrderFile orderFile : orderFiles) { + String viewUrl = fileCenterService.getFileViewUrl(orderFile.getFileId()); + orderFile.setViewUrl(viewUrl); + } + }else { + return Result.failed("暂无数据"); + } + return null; + } + + @Operation(summary = "设备回传照片path记录创建") + @PostMapping("/path") + public Result createOrderFileForPath(@RequestBody OrderFile orderFile) { + + if (orderFile != null && orderFile.getOrderNo() != null) { + Order order = orderService.getOrderByNumber(orderFile.getOrderNo()); + orderFile.setOrderNo(order.getOrderNo()); + orderFile.setUserId(order.getUserId()); + if (orderFile.getFilePath() != null) { + + FileInfo fileInfo = fileCenterService.creatFileInfo(orderFile.getFilePath()); + orderFile.setFileId(fileInfo.getId()); + orderFile.setFilePath(fileInfo.getPath()); + orderFile.setFileType(fileInfo.getContentType()); + orderFile.setTourismId(order.getTourismId()); + } + if (orderFileService.save(orderFile)){ + // 机库上报订单素材,更新订单状态为素材上传中,如果订单为设备执行中则更新,否则说明状态已更新 + if (order.getOrderStatus().equals(OrderStatus.DOING.getId()) + || order.getOrderStatus().equals(OrderStatus.PAID.getId())) { + order.setOrderStatus(OrderStatus.UPLOADING.getId()); + orderService.updateOrder(order); + } + return Result.succeed(order,"更新成功"); + } + } + return Result.failed("素材内容为空"); + + } + + @Operation(summary = "删除文件") + @DeleteMapping( "/{id}") + public Result delete(@PathVariable Long id) { + + if (orderFileService.delete(id) > 0){ + return Result.succeed("删除成功"); + } + return Result.failed("删除失败"); + + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderStatisticsController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderStatisticsController.java new file mode 100644 index 00000000..2af2eeba --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderStatisticsController.java @@ -0,0 +1,102 @@ +package com.central.order.controller; + +import com.central.common.model.Result; +import com.central.order.service.IOrderStatisticsService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/statistics") +@Tag(name = "订单统计", description = "订单多维度统计接口") +@RequiredArgsConstructor +public class OrderStatisticsController { + + private final IOrderStatisticsService orderStatisticsService; + + @Operation(summary = "生成统计数据", description = "根据时间范围生成订单统计数据") + @Parameters({ + @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true) + }) + @PostMapping("/generate") + public Result generateStatistics( + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) { + try { + boolean result = orderStatisticsService.generateStatistics(startTime, endTime); + return result ? Result.succeed("统计数据生成成功") : Result.failed("统计数据生成失败"); + } catch (Exception e) { + log.error("生成统计数据失败", e); + return Result.failed("生成统计数据时发生错误:" + e.getMessage()); + } + } + + @Operation(summary = "按时间维度统计", description = "统计指定二维码在时间范围内的订单数据") + @Parameters({ + @Parameter(name = "qrcodeId", description = "二维码ID", required = true), + @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "timeType", description = "时间维度类型(hour/day/month)", required = false) + }) + @GetMapping("/time") + public Result>> statisticsByTime( + @RequestParam String qrcodeId, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime, + @RequestParam(defaultValue = "day") String timeType) { + try { + List> result = orderStatisticsService.statisticsByTime( + qrcodeId, startTime, endTime, timeType); + return Result.succeed(result, "获取时间维度统计数据成功"); + } catch (Exception e) { + log.error("获取时间维度统计数据失败", e); + return Result.failed("获取统计数据时发生错误:" + e.getMessage()); + } + } + + @Operation(summary = "按景区维度统计", description = "统计时间范围内各景区的订单数据") + @Parameters({ + @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true) + }) + @GetMapping("/tourism") + public Result>> statisticsByTourism( + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) { + try { + List> result = orderStatisticsService.statisticsByTourism(startTime, endTime); + return Result.succeed(result, "获取景区维度统计数据成功"); + } catch (Exception e) { + log.error("获取景区维度统计数据失败", e); + return Result.failed("获取统计数据时发生错误:" + e.getMessage()); + } + } + + @Operation(summary = "按设备维度统计", description = "统计时间范围内各设备的订单数据") + @Parameters({ + @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true) + }) + @GetMapping("/device") + public Result>> statisticsByDevice( + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) { + try { + List> result = orderStatisticsService.statisticsByDevice(startTime, endTime); + return Result.succeed(result, "获取设备维度统计数据成功"); + } catch (Exception e) { + log.error("获取设备维度统计数据失败", e); + return Result.failed("获取统计数据时发生错误:" + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/PaymentRecordController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/PaymentRecordController.java new file mode 100644 index 00000000..fa229ab0 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/PaymentRecordController.java @@ -0,0 +1,57 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.service.IPaymentRecordService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * Payment information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "支付记录管理") +@RequestMapping("/payment") +@RequiredArgsConstructor +public class PaymentRecordController { + + @Autowired + private IPaymentRecordService paymentRecordService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return paymentRecordService.findList(params); + } + + // 接收前端传来的订单编号和支付金额,处理订单支付 + @PostMapping + public Result processPayment(@RequestParam String orderNumber, @RequestParam Double paymentAmount) { + boolean result = paymentRecordService.processPayment(orderNumber, paymentAmount); + if (result) { + return Result.succeed("订单支付成功"); + } else { + return Result.failed("订单支付失败"); + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/ProfitSharingController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/ProfitSharingController.java new file mode 100644 index 00000000..bf810ed2 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/ProfitSharingController.java @@ -0,0 +1,62 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.ProfitSharing; +import com.central.order.model.vo.ProfitSharingStatisticsVO; +import com.central.order.service.IProfitSharingService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/profitSharing") +@Tag(name = "分账管理") +@RequiredArgsConstructor +public class ProfitSharingController { + + private final IProfitSharingService profitSharingService; + + @Operation(summary = "分页查询分账记录") + @GetMapping("/list") + public PageResult list(@RequestParam Map params) { + return profitSharingService.findList(params); + } + + @Operation(summary = "获取分账记录详情") + @GetMapping("/{orderNo}") + public Result detail(@PathVariable String orderNo) { + ProfitSharing profitSharing = profitSharingService.getByOrderNo(orderNo); + return Result.succeed(profitSharing); + } + + @Operation(summary = "手动触发分账") + @PostMapping("/execute/{orderNo}") + public Result executeProfitSharing(@PathVariable String orderNo) { + try { + profitSharingService.executeProfitSharing(orderNo); + return Result.succeed("分账执行成功"); + } catch (Exception e) { + log.error("手动触发分账失败", e); + return Result.failed("分账执行失败:" + e.getMessage()); + } + } + + @Operation(summary = "获取分账统计数据") + @GetMapping("/statistics") + public Result getStatistics() { + try { + ProfitSharingStatisticsVO statistics = profitSharingService.getStatistics(); + return Result.succeed(statistics); + } catch (Exception e) { + log.error("获取分账统计数据失败", e); + return Result.failed("获取统计数据失败"); + } + } +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/QrCodeController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/QrCodeController.java new file mode 100644 index 00000000..877f4e7f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/QrCodeController.java @@ -0,0 +1,149 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.feign.FileCenterService; +import com.central.order.model.*; +import com.central.order.service.IOrderService; +import com.central.order.service.IQrCodeService; +import com.central.order.service.ITourismFileService; +import com.central.order.service.ITourismService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.Assert; +import org.springframework.util.CollectionUtils; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * qrcode information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "二维码管理") +@RequestMapping("/qrcode") +@RequiredArgsConstructor +public class QrCodeController { + + @Autowired + private IQrCodeService qrCodeService; + + @Autowired + private FileCenterService fileCenterService; + + @Autowired + private ITourismService tourismService; + + @Autowired + private ITourismFileService tourismFileService; + + @Autowired + private IOrderService orderService; + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + PageResult pageResult = qrCodeService.findList(params); + if (pageResult.getResp_code() == 0){ + for (QrCode qrCode: pageResult.getData()){ + qrCode.setViewUrl(fileCenterService.getViewUrlByPath(qrCode.getFilePath())); + } + } + return pageResult; + } + + @Operation(summary = "生成景区二维码") + @PostMapping + public Result saveOrUpdateQrcode(@RequestBody QrCode qrCode) throws Exception { + + if (qrCode.getId() == null){ + String codeId = UUID.randomUUID().toString(); + Result result = fileCenterService.uploadQrCodeFile(codeId); + if (result.getResp_code() == 0){ + qrCode.setCodeId(codeId); + qrCode.setFilePath(result.getData().get("filePath").toString()); + qrCode.setFileId(result.getData().get("fileId").toString()); + if (qrCodeService.saveOrUpdate(qrCode)) { + return Result.succeed(qrCode,"qrcode创建成功"); + } else { + return Result.failed("qrcode创建失败"); + } + } + }else { + qrCodeService.saveOrUpdate(qrCode); + return Result.succeed(qrCode,"qrcode修改成功"); + } + return Result.failed("创建失败"); + + } + + @Operation(summary = "根据code查询二维码信息") + @GetMapping("/{codeId}") + public Result getQrCode(@PathVariable("codeId") String codeId) { + QrCode qrCode = qrCodeService.getByCodeId(codeId); + if (qrCode == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(qrCode,"获取成功"); + } + + @Operation(summary = "根据code查询二维码信息") + @GetMapping("/info/{codeId}") + public Result getQrCodeInfo(@PathVariable("codeId") String codeId) { + QrCode qrCode = qrCodeService.getByCodeId(codeId); + Assert.notNull(qrCode,"QRCODE不能为空"); + Tourism tourism = tourismService.getTourismById(qrCode.getTourismId()); + Assert.notNull(tourism,"TOURISM数据不能为空"); + List tourismFiles = tourismFileService.getByTourismId(qrCode.getTourismId()); + if (!CollectionUtils.isEmpty(tourismFiles)) { + for (TourismFile tourismFile: tourismFiles) { + tourismFile.setImageUrl(fileCenterService.getViewUrlByPath(tourismFile.getImageUrl())); + } + } + QrCodeVO qrCodeVO = new QrCodeVO(); + qrCodeVO.setCodeId(codeId); + qrCodeVO.setTourism(tourism); + qrCodeVO.setTourismFiles(tourismFiles); + return Result.succeed(qrCodeVO,"获取成功"); + } + + + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + qrCodeService.removeById(id); + return Result.succeed("操作成功"); + } + + @GetMapping("/wayline/{orderNo}") + public Map getWaylineByOrderNo(@PathVariable("orderNo") String orderNo){ + + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单No不能为空"); + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + Assert.notNull(qrCode,"二维码数据不能为空"); + String waylineFilePath = fileCenterService.getFileViewUrl(qrCode.getWaylineId()); + Map map = new HashMap<>(); + map.put("waylineFilePath",waylineFilePath); + map.put("waylineId",qrCode.getWaylineId()); + return map; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/RefundController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/RefundController.java new file mode 100644 index 00000000..a2a8bd0b --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/RefundController.java @@ -0,0 +1,146 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.enums.OrderStatus; +import com.central.order.enums.RefundState; +import com.central.order.model.Order; +import com.central.order.service.IOrderService; +import com.central.order.service.IRefundService; +import com.central.wechat.config.WxPayConfigFactory; +import com.wechat.pay.java.service.refund.model.AmountReq; +import com.wechat.pay.java.service.refund.model.CreateRequest; +import com.wechat.pay.java.service.refund.model.Refund; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@RestController +@RequestMapping("/refund") +public class RefundController { + + @Autowired + private WxPayConfigFactory wxPayConfigFactory; + + @Autowired + private IOrderService orderService; + + @Autowired + private IRefundService refundService; + + @Value("${tencent.refund-notify-url}") + private String refundNotifyUrl; + + /** + * 列表 + */ + @Operation(summary = "查询全部列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in= ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping() + public PageResult list(@RequestParam Map params) { + return refundService.findList(params); + } + + @Operation(summary = "创建退款单") + @PostMapping("/{orderNo}") + public Result createRefundOrder(@PathVariable String orderNo,@RequestBody com.central.order.model.Refund refundBody) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"ORDER DATA不存在"); + if (order.getOrderStatus().equals(OrderStatus.PAID.getId()) + || order.getOrderStatus().equals(OrderStatus.COMPLETE.getId()) + || order.getOrderStatus().equals(OrderStatus.DOING.getId())) { + // 创建退款订单 + com.central.order.model.Refund refund = new com.central.order.model.Refund(); + refund.setRefundNo("RF" + order.getOrderNo()); + com.central.order.model.Refund existRefund = refundService.getRefundByNo(refund.getRefundNo()); + if (existRefund != null){ + return Result.succeed("已提交"); + } + refund.setOrderNo(order.getOrderNo()); + refund.setUserId(order.getUserId()); + refund.setOrderAmount(order.getOrderAmount()); + refund.setRefundAmount(order.getOrderAmount()); + refund.setStatus(OrderStatus.REFUNDING.getId()); + refund.setState(RefundState.APPROVING.getId()); + refund.setRefundReason(refundBody.getRefundReason()); + refund.setRefundImgs(refundBody.getRefundImgs()); + boolean res = refundService.createRefund(refund); + if (res) { + order.setOrderStatus(OrderStatus.REFUNDING.getId()); + orderService.updateOrder(order); + return Result.succeed("退款成功"); + } + return Result.failed("请重试"); + }else { + return Result.failed("该订单不支持退款操作"); + } + } + + @Operation(summary = "微信支付退款") + @PostMapping("/approve") + @Transactional(rollbackFor = Exception.class) + public Result approveOrder(@RequestBody com.central.order.model.Refund refund) { + + // 检查订单是否存在 + Order order = orderService.getOrderByNumber(refund.getOrderNo()); + Assert.notNull(order, "ORDER DATA不存在"); + if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){ + return Result.failed("请重试"); + } + if (! refund.getStatus().equals(OrderStatus.REFUNDING.getId())){ + return Result.failed("该状态不支持审核"); + } + if (refund.getState().equals(RefundState.APPROVED.getId())){ + dealRefundRequest(order); + return Result.succeed("已处理退款"); + } + if (refund.getState().equals(RefundState.REFUSED.getId())){ + order.setOrderStatus(OrderStatus.REFUND_FAILED.getId()); + refund.setStatus(OrderStatus.REFUND_FAILED.getId()); + orderService.updateOrder(order); + refundService.updateById(refund); + return Result.succeed("处理成功"); + } + return Result.failed("处理退款失败"); + } + + private void dealRefundRequest(Order order) { + try { + // 创建微信退款请求 + CreateRequest request = new CreateRequest(); + request.setOutTradeNo(order.getOrderNo()); + request.setOutRefundNo("RF" + order.getOrderNo()); + request.setReason("用户申请退款"); + // 从配置文件中获取退款结果回调通知地址 + request.setNotifyUrl(refundNotifyUrl); + + // 设置退款金额 + AmountReq amount = new AmountReq(); + // 订单总金额,单位为分 + amount.setTotal(Long.valueOf(order.getOrderAmount())); + // 退款金额,单位为分 + amount.setRefund(Long.valueOf(order.getOrderAmount())); + amount.setCurrency("CNY"); + request.setAmount(amount); + + // 发起退款请求 + Refund response = wxPayConfigFactory.createRefundService(order.getTenantId()).create(request); + Assert.notNull(response, "退款失败"); + } catch (Exception e) { + // 记录异常信息 + e.printStackTrace(); + } + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/TourismController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/TourismController.java new file mode 100644 index 00000000..a370d51d --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/TourismController.java @@ -0,0 +1,69 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.Tourism; +import com.central.order.service.ITourismService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * Tourism information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "Tourism管理") +@RequestMapping("/tourism") +@RequiredArgsConstructor +public class TourismController { + + @Autowired + private ITourismService tourismService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return tourismService.findList(params); + } + + @PostMapping() + public Result saveOrUpdate(@RequestBody Tourism tourism) { + return tourismService.saveOrUpdateTourism(tourism); + } + + @Operation(summary = "查询Tourism") + @GetMapping("/{id}") + public Result getTourism(@PathVariable("id") Long id) { + Tourism tourism = tourismService.getTourismById(id); + if (tourism == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(tourism,"获取成功"); + } + + @DeleteMapping() +// @AuditLog(operation = "'新增或更新用户:' + #sysUser.username") + public Result delete(@RequestBody Tourism tourism) { + boolean result = tourismService.removeById(tourism); + return result ? Result.succeed(tourism, "操作成功") : Result.failed("操作失败"); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/TourismFileController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/TourismFileController.java new file mode 100644 index 00000000..f3ae755c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/TourismFileController.java @@ -0,0 +1,78 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.feign.FileCenterService; +import com.central.order.model.TourismFile; +import com.central.order.service.ITourismFileService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * Tourism File information + * + * @author lsl + * @date 2025-2-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "TourismFile管理") +@RequestMapping("/tourism/files") +@RequiredArgsConstructor +public class TourismFileController { + + @Autowired + private ITourismFileService tourismFileService; + + @Autowired + private FileCenterService fileCenterService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + PageResult pageResult = tourismFileService.findList(params); + if (pageResult.getCount()>0){ + for (TourismFile tourismFile: pageResult.getData()){ + tourismFile.setImageUrl(fileCenterService.getViewUrlByPath(tourismFile.getImageUrl())); + } + } + return pageResult; + } + + @PostMapping() + public Result saveOrUpdate(@RequestBody TourismFile tourismFile) { + return tourismFileService.saveOrUpdateTourismFile(tourismFile); + } + + @Operation(summary = "查询TourismFile") + @GetMapping("/{id}") + public Result getTourismFile(@PathVariable("id") Long id) { + TourismFile tourismFile = tourismFileService.getById(id); + if (tourismFile == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(tourismFile,"获取成功"); + } + + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + tourismFileService.removeById(id); + return Result.succeed( "操作成功"); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/VideoTemplateController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/VideoTemplateController.java new file mode 100644 index 00000000..70c14cd4 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/VideoTemplateController.java @@ -0,0 +1,95 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.VideoTemplate; +import com.central.order.service.IVideoTemplateService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("/video/template") +@Tag(name = "视频模板管理") +public class VideoTemplateController { + + private final IVideoTemplateService videoTemplateService; + + @Operation(summary = "分页查询模板") + @GetMapping("/list") + public Result> list(@RequestParam Map params) { + try { + PageResult result = videoTemplateService.findList(params); + return Result.succeed(result); + } catch (Exception e) { + log.error("查询模板列表失败", e); + return Result.failed("查询失败"); + } + } + + @Operation(summary = "添加模板") + @PostMapping + public Result save(@RequestBody VideoTemplate template) { + try { + boolean result = videoTemplateService.saveTemplate(template); + return Result.succeed(result); + } catch (Exception e) { + log.error("添加模板失败", e); + return Result.failed("添加失败"); + } + } + + @Operation(summary = "更新模板") + @PutMapping + public Result update(@RequestBody VideoTemplate template) { + try { + boolean result = videoTemplateService.updateTemplate(template); + return Result.succeed(result); + } catch (Exception e) { + log.error("更新模板失败", e); + return Result.failed("更新失败"); + } + } + + @Operation(summary = "删除模板") + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + try { + boolean result = videoTemplateService.deleteTemplate(id); + return Result.succeed(result); + } catch (Exception e) { + log.error("删除模板失败", e); + return Result.failed("删除失败"); + } + } + + @Operation(summary = "更新模板状态") + @PutMapping("/{id}/status/{status}") + public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) { + try { + boolean result = videoTemplateService.updateStatus(id, status); + return Result.succeed(result); + } catch (Exception e) { + log.error("更新模板状态失败", e); + return Result.failed("更新状态失败"); + } + } + + @Operation(summary = "获取可用模板") + @GetMapping("/active") + public Result getActiveTemplate() { + try { + VideoTemplate template = videoTemplateService.getActiveTemplate(); + return Result.succeed(template); + } catch (Exception e) { + log.error("获取可用模板失败", e); + return Result.failed("获取失败"); + } + } +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/WxCallbackController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/WxCallbackController.java new file mode 100644 index 00000000..288ff0b5 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/WxCallbackController.java @@ -0,0 +1,58 @@ +package com.central.order.controller; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.security.MessageDigest; +import java.util.Arrays; + +/** + * + * 服务号调用API + * @author lsl + * @date 2025-04-24 + * + */ + +@Slf4j +@RestController +@RequestMapping("/token/callback") +@RequiredArgsConstructor +public class WxCallbackController { + + private static final String TOKEN = "codechangetheworld2025"; //MIUFvX040zDQtUHUGEFjpzDwgNLmPe6gWPVsnQMW3nL + + @GetMapping() + public String verify( + @RequestParam("signature") String signature, + @RequestParam("timestamp") String timestamp, + @RequestParam("nonce") String nonce, + @RequestParam("echostr") String echostr) throws Exception { + + log.info("开始验证微信token请求:{}", signature); + // 1. 字典序排序并拼接 + String[] arr = {TOKEN, timestamp, nonce}; + Arrays.sort(arr); + String rawStr = String.join("", arr); + + // 2. SHA1 加密 + MessageDigest md = MessageDigest.getInstance("SHA-1"); + byte[] digest = md.digest(rawStr.getBytes()); + StringBuilder sb = new StringBuilder(); + for (byte b : digest) { + sb.append(String.format("%02x", b)); + } + String hash = sb.toString(); + + // 3. 校验签名 + if (hash.equals(signature)) { + return echostr; + } else { + return "Invalid signature"; + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/WxMessageRecordController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/WxMessageRecordController.java new file mode 100644 index 00000000..67c7dfe5 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/WxMessageRecordController.java @@ -0,0 +1,54 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.WxMessageRecord; +import com.central.order.service.IWxMessageRecordService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDateTime; +import java.util.Map; + +@Slf4j +@RestController +@Tag(name = "微信消息记录管理") +@RequestMapping("/wx/message") +public class WxMessageRecordController { + + @Autowired + private IWxMessageRecordService messageRecordService; + + @Operation(summary = "分页查询消息记录") + @GetMapping("/records") + public PageResult records(@RequestParam Map params) { + return messageRecordService.findRecords(params); + } + + @Operation(summary = "获取消息统计") + @GetMapping("/statistics") + public Result> statistics( + @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime, + @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) { + if (startTime == null) { + startTime = LocalDateTime.now().minusDays(7); + } + if (endTime == null) { + endTime = LocalDateTime.now(); + } + return Result.succeed(messageRecordService.getStatistics(startTime, endTime)); + } + + @Operation(summary = "获取失败消息记录") + @GetMapping("/failed") + public Result getFailedRecords() { + return Result.succeed(messageRecordService.getFailedRecords()); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/WxPayController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/WxPayController.java new file mode 100644 index 00000000..8fe3c816 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/WxPayController.java @@ -0,0 +1,490 @@ +package com.central.order.controller; + +import com.central.order.constants.ProfitSharingConstants; +import com.central.order.enums.OrderStatus; +import com.central.order.enums.RefundState; +import com.central.order.model.Order; +import com.central.order.model.ProfitSharing; +import com.central.order.model.QrCode; +import com.central.order.service.IOrderService; +import com.central.order.service.IProfitSharingService; +import com.central.order.service.IQrCodeService; +import com.central.order.service.IRefundService; +import com.central.wechat.config.WxPayConfigFactory; +import com.central.wechat.entity.WechatConfig; +import com.central.wechat.feign.WechatConfigService; +import com.wechat.pay.java.core.notification.NotificationParser; +import com.wechat.pay.java.core.notification.RequestParam; +import com.wechat.pay.java.service.payments.model.Transaction; +import com.wechat.pay.java.service.refund.model.RefundNotification; +import com.wechat.pay.java.service.refund.model.Status; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.*; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Slf4j +@RestController +@Tag(name = "支付管理") +@RequestMapping("/wechat") +public class WxPayController { + + @Autowired + private IOrderService orderService; + @Autowired + private IRefundService refundService; + @Autowired + private IQrCodeService qrCodeService; + @Autowired + private IProfitSharingService profitSharingService; + + @Autowired + private WxPayConfigFactory wxPayConfigFactory; + + @Autowired + private WechatConfigService wechatConfigService; + + @Value("${zlt.tenant.id}") + private String defaultTenantId; + + @PostMapping("/pay/notify") + public String handleCallback(@RequestHeader("Wechatpay-Signature") String signature, + @RequestHeader("Wechatpay-Timestamp") String timestamp, + @RequestHeader("Wechatpay-Nonce") String nonce, + @RequestHeader("Wechatpay-Serial") String serial, + @RequestBody String body) { + + try { + // 构建请求参数 + RequestParam requestParam = new RequestParam + .Builder() + .body(body) + .nonce(nonce) + .signature(signature) + .serialNumber(serial) + .timestamp(timestamp) + .build(); + log.info("------收到微信支付成功回调通知------"); + log.info(requestParam.toString()); + // @TODO 后面需要将订单号和租户ID缓存进行处理,或者其他方式,目前先使用默认的tenantID,退款也是同样的问题 + WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial); + String tenantId = defaultTenantId; + if (config != null) { + tenantId = config.getTenantId(); + } + + NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser(tenantId); + // 解析通知 + Transaction transaction = notificationParser.parse(requestParam,Transaction.class); + + // 处理支付结果 + handlePaymentResult(transaction); + + // 返回成功响应 + return "{\"code\":\"SUCCESS\",\"message\":\"成功\"}"; + } catch (Exception e) { + // 处理异常,记录日志等 + e.printStackTrace(); + return "{\"code\":\"FAIL\",\"message\":\"失败\"}"; + } + } + + private void handlePaymentResult(Transaction transaction) { + String outTradeNo = transaction.getOutTradeNo(); + String tradeState = transaction.getTradeState().toString(); + + try { + if ("SUCCESS".equals(tradeState)) { + // 1. 获取订单和二维码信息 + Order order = orderService.getOrderByNumber(outTradeNo); + if (order == null) { + log.error("订单不存在: {}", outTradeNo); + return; + } + + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (qrCode == null) { + log.error("二维码不存在: {}", order.getCodeId()); + return; + } + + // 2. 更新订单状态 + order.setOrderStatus(OrderStatus.PAID.getId()); + order.setPayTime(new Date()); + orderService.updateOrder(order); + + // 3. 处理分账 + if (isEnableProfit(qrCode)) { + try { + // 更新分账记录的微信支付订单号 + profitSharingService.updateTransactionId( + outTradeNo, + transaction.getTransactionId() + ); + + // 发起分账 + profitSharingService.executeProfitSharing(outTradeNo); + } catch (Exception e) { + log.error("处理分账失败: orderNo={}", outTradeNo, e); + // 分账失败不影响支付结果,但需要记录并告警 + sendProfitSharingAlert(order, e.getMessage()); + } + } + } else { + log.info("支付未成功: orderNo={}, state={}", outTradeNo, tradeState); + } + } catch (Exception e) { + log.error("处理支付结果异常: orderNo={}", outTradeNo, e); + throw e; + } + } + + /** + * 检查是否开启分润 + */ + private boolean isEnableProfit(QrCode qrCode) { + return qrCode != null && + Integer.valueOf(1).equals(qrCode.getEnableProfit()) && + qrCode.getPayeeStatus() != null && + qrCode.getPayeeStatus() == 1 && // 确保分账账号已验证 + qrCode.getPayeeAccount() != null && // 确保有收款账号 + qrCode.getProfitRate() != null; // 确保有分润比例 + } + + /** + * 发送分账异常告警 + */ + private void sendProfitSharingAlert(Order order, String errorMessage) { + try { + String alertMessage = String.format( + "分账处理异常告警\n" + + "订单号:%s\n" + + "异常信息:%s\n" + + "时间:%s", + order.getOrderNo(), + errorMessage, + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ); + + log.error(alertMessage); + // TODO: 实现具体的告警通知逻辑 + } catch (Exception e) { + log.error("发送分账异常告警失败", e); + } + } + + @PostMapping("/refund/notify") + public String refundCallback(@RequestHeader("Wechatpay-Signature") String signature, + @RequestHeader("Wechatpay-Timestamp") String timestamp, + @RequestHeader("Wechatpay-Nonce") String nonce, + @RequestHeader("Wechatpay-Serial") String serial, + @RequestBody String body) { + log.info("------收到微信退款回调通知------"); + try { + // 构建请求参数 + RequestParam requestParam = new RequestParam + .Builder() + .body(body) + .nonce(nonce) + .signature(signature) + .serialNumber(serial) + .timestamp(timestamp) + .build(); + + WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial); + String tenantId = defaultTenantId; + if (config != null) { + tenantId = config.getTenantId(); + } + + NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser(tenantId); + // 解析通知 + RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class); + + // 处理退款结果 + handleRefundResult(notification); + + // 返回成功响应 + return buildSuccessResponse(); + } catch (Exception e) { + // 处理异常,记录日志等 + e.printStackTrace(); + return buildErrorResponse(); + } + } + + /** + * 构建请求参数 + */ + private RequestParam buildRequestParam(Map headers, String body) { + return new RequestParam.Builder() + .serialNumber(headers.get("Wechatpay-Serial")) + .nonce(headers.get("Wechatpay-Nonce")) + .signature(headers.get("Wechatpay-Signature")) + .timestamp(headers.get("Wechatpay-Timestamp")) + .body(body) + .build(); + } + + /** + * 解析通知数据 + */ + private ProfitSharingNotification parseNotification(RequestParam requestParam) { + try { + NotificationParser parser = wxPayConfigFactory.createNotificationParser(defaultTenantId); + // 解析为Map后转换为ProfitSharingNotification对象 + Map result = parser.parse(requestParam, Map.class); + + ProfitSharingNotification notification = new ProfitSharingNotification(); + notification.setMchid((String) result.get("mchid")); + notification.setTransactionId((String) result.get("transaction_id")); + notification.setOutOrderNo((String) result.get("out_order_no")); + notification.setState((String) result.get("state")); + notification.setFailReason((String) result.get("fail_reason")); + + // 处理接收方列表 + if (result.containsKey("receivers")) { + List> receiversMap = (List>) result.get("receivers"); + List receivers = new ArrayList<>(); + + for (Map receiverMap : receiversMap) { + ProfitSharingNotification.Receiver receiver = new ProfitSharingNotification.Receiver(); + receiver.setType((String) receiverMap.get("type")); + receiver.setAccount((String) receiverMap.get("account")); + receiver.setAmount(Long.valueOf(receiverMap.get("amount").toString())); + receiver.setDescription((String) receiverMap.get("description")); + receiver.setResult((String) receiverMap.get("result")); + receiver.setFailReason((String) receiverMap.get("fail_reason")); + receiver.setDetailId((String) receiverMap.get("detail_id")); + receivers.add(receiver); + } + notification.setReceivers(receivers); + } + + return notification; + } catch (Exception e) { + log.error("解析分账回调通知失败", e); + throw new RuntimeException("解析分账回调通知失败", e); + } + } + + /** + * 优化后的分账回调处理方法 + */ + @PostMapping("/profitsharing/notify") + public String handleProfitSharingNotify(@RequestHeader Map headers, + @RequestBody String body) { + log.info("收到分账回调通知: headers={}, body={}", headers, body); + + try { + // 1. 验证通知签名 + RequestParam requestParam = buildRequestParam(headers, body); + + // 2. 解析通知数据 + ProfitSharingNotification notification = parseNotification(requestParam); + + // 3. 处理分账结果 + handleProfitSharingNotification(notification); + + // 4. 返回成功响应 + return buildSuccessResponse(); + + } catch (Exception e) { + log.error("处理分账回调失败", e); + return buildErrorResponse(); + } + } + + private void handleProfitSharingNotification(ProfitSharingNotification notification) { + String orderNo = notification.getOutOrderNo(); + String state = notification.getState(); + + try { + // 1. 获取分账记录 + ProfitSharing profitSharing = profitSharingService.getByOrderNo(orderNo); + if (profitSharing == null) { + log.error("分账记录不存在: {}", orderNo); + return; + } + + // 2. 根据状态处理 + switch (state) { + case "FINISHED": + // 分账成功 + handleProfitSharingSuccess(profitSharing, notification); + break; + + case "FAILED": + // 分账失败 + handleProfitSharingFailure(profitSharing, notification); + break; + + default: + log.warn("未知的分账状态: orderNo={}, state={}", orderNo, state); + } + } catch (Exception e) { + log.error("处理分账回调异常: orderNo={}", orderNo, e); + // 确保更新状态 + profitSharingService.updateProfitSharingStatus( + orderNo, + ProfitSharingConstants.Status.FAILED + ); + } + } + + /** + * 处理分账成功 + */ + private void handleProfitSharingSuccess(ProfitSharing profitSharing, + ProfitSharingNotification notification) { + // 1. 更新分账状态 + profitSharing.setStatus(ProfitSharingConstants.Status.SUCCESS); + profitSharing.setFinishTime(new Date()); + + // 2. 如果有接收方信息,更新接收方结果 + if (notification.getReceivers() != null && !notification.getReceivers().isEmpty()) { + ProfitSharingNotification.Receiver receiver = notification.getReceivers().get(0); + profitSharing.setReceiverAmount(receiver.getAmount()); + profitSharing.setProfitSharingId(receiver.getDetailId()); + } + + // 3. 保存更新 + profitSharingService.updateById(profitSharing); + + log.info("分账成功: orderNo={}", profitSharing.getOrderNo()); + } + + /** + * 处理分账失败 + */ + private void handleProfitSharingFailure(ProfitSharing profitSharing, + ProfitSharingNotification notification) { + // 1. 更新分账状态和失败原因 + profitSharing.setStatus(ProfitSharingConstants.Status.FAILED); + profitSharing.setFailReason(notification.getFailReason()); + profitSharing.setUpdateTime(new Date()); + + // 2. 判断是否需要重试 + if (profitSharing.canRetry()) { + log.info("准备重试分账: orderNo={}, retryTimes={}", + profitSharing.getOrderNo(), profitSharing.getRetryTimes()); + + // 更新重试信息 + profitSharing.setRetryTimes(profitSharing.getRetryTimes() + 1); + profitSharing.setLastRetryTime(new Date()); + profitSharingService.updateById(profitSharing); + + // 发起重试 + profitSharingService.retryFailedProfitSharing(profitSharing.getOrderNo()); + } else { + log.warn("分账失败且不再重试: orderNo={}, retryTimes={}", + profitSharing.getOrderNo(), profitSharing.getRetryTimes()); + + // 发送告警 + sendFailureAlert(profitSharing); + + // 保存最终状态 + profitSharingService.updateById(profitSharing); + } + } + + /** + * 发送失败告警 + */ + private void sendFailureAlert(ProfitSharing profitSharing) { + try { + String alertMessage = String.format( + "分账失败告警\n" + + "订单号:%s\n" + + "交易号:%s\n" + + "失败原因:%s\n" + + "重试次数:%d\n" + + "分账金额:%d分\n" + + "失败时间:%s", + profitSharing.getOrderNo(), + profitSharing.getTransactionId(), + profitSharing.getFailReason(), + profitSharing.getRetryTimes(), + profitSharing.getQrCodeAmount(), + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ); + + log.error(alertMessage); + // TODO: 实现具体的告警通知逻辑,如发送邮件、钉钉消息等 + + } catch (Exception e) { + log.error("发送分账失败告警异常", e); + } + } + + /** + * 退款订单结果处理逻辑 + * @param notification + */ + private void handleRefundResult(RefundNotification notification) { + // 获取退款通知中的关键信息 + String outRefundNo = notification.getOutRefundNo(); + + log.info("回调返回结果"+notification); + // 根据退款状态进行相应处理 + if (Status.SUCCESS.equals(notification.getRefundStatus())) { + // 退款成功,更新订单状态等操作 + com.central.order.model.Refund refund = refundService.getRefundByNo(outRefundNo); + Assert.notNull(refund,"退款订单数据不存在"); + refund.setStatus(OrderStatus.REFUNDED.getId()); + refund.setState(RefundState.APPROVED.getId()); + refund.setRefundTime(new Date()); + refundService.updateById(refund); + + Order order = orderService.getOrderByNumber(refund.getOrderNo()); + Assert.notNull(order,"订单数据不存在"); + order.setOrderStatus(OrderStatus.REFUNDED.getId()); + orderService.updateOrder(order); + } else if ("CLOSED".equals(notification.getRefundStatus())) { + // 退款关闭,处理退款关闭逻辑 + } else { + // 其他退款状态,如退款中、失败等 + } + } + + private String buildSuccessResponse() { + return "{\"code\":\"SUCCESS\",\"message\":\"成功\"}"; + } + + private String buildErrorResponse() { + return "{\"code\":\"FAIL\",\"message\":\"失败\"}"; + } +} + +/** + * 分账通知解析实体类 + */ +@Data +class ProfitSharingNotification { + private String mchid; // 商户号 + private String transactionId; // 微信订单号 + private String outOrderNo; // 商户分账单号 + private String state; // 分账状态 + private String failReason; // 失败原因 + private List receivers; // 分账接收方列表 + + @Data + public static class Receiver { + private String type; // 分账接收方类型 + private String account; // 分账接收方账号 + private Long amount; // 分账金额 + private String description; // 分账描述 + private String result; // 分账结果 + private String failReason; // 分账失败原因 + private String detailId; // 分账明细单号 + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/WxTestController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/WxTestController.java new file mode 100644 index 00000000..967832bb --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/WxTestController.java @@ -0,0 +1,39 @@ +package com.central.order.controller; + +import com.central.common.model.Result; +import com.central.order.service.IWxTemplateMessageService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RestController +@RequestMapping("/wx/test") +@RequiredArgsConstructor +public class WxTestController { + + private final IWxTemplateMessageService templateMessageService; + + @GetMapping("/template/send") + public Result testSendTemplate( + @RequestParam String openId, + @RequestParam String orderNo, + @RequestParam String serviceName, + @RequestParam Integer rank) { + try { + + + // 发送消息 + templateMessageService.sendPaymentSuccessNotice( + openId, orderNo, serviceName, rank); + + return Result.succeed("发送成功"); + } catch (Exception e) { + log.error("发送模板消息失败", e); + return Result.failed("发送失败:" + e.getMessage()); + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/orderStatusLogic.md b/zlt-business/order-center/src/main/java/com/central/order/controller/orderStatusLogic.md new file mode 100644 index 00000000..01a83b59 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/orderStatusLogic.md @@ -0,0 +1,46 @@ +1. 待支付 +说明:用户成功提交订单,但尚未完成支付操作。此状态下,订单处于暂挂状态,可能因为用户还在选择支付方式、支付过程中出现问题等原因导致未支付。 +操作:用户可选择支付、取消订单;商家可设置订单自动取消时间,超时未支付则订单自动取消。 + +2. 已取消 +说明:订单在支付前被用户主动取消,或者因超过规定的支付时间而被系统自动取消。 +操作:一般无后续操作,订单流程结束。 + +3. 支付成功 +说明:用户成功完成支付,订单进入待处理排队(此时的状态也称作排队中)阶段。 +操作:商家开始处理订单,如确认设备状态;系统可发送支付成功通知给用户。 + +4. 设备执行中 +说明:商家正在对订单进行处理调度设备作业,包括但不限于确认订单信息、设备作业状态、设备素材上传等操作。 +操作:商家完成处理后,可将订单状态更新为素材上传完成或素材上传中(对于多素材订单)。 + +5. 素材上传中 +说明:商家已将照片上传。用户可以通过订单号查询订单对应素材。 +操作:商家上传照片中,用户可查询上传进度。 + +6. 素材上传完成 +说明:订单上传素材完成,处于用户下载状态。 +操作:用户可查询素材信息并进行下载操作;若出现上传异常,商家需及时处理。 + +7. 用户已下载完成 +说明:用户确认订单素材并下载完成且可能已完成评价,整个订单流程结束。 +操作:无后续主要操作,可作为历史订单进行存档和统计分析。 + +8. 退款中 +说明:用户发起退款申请,商家或平台正在处理该申请。 +操作:商家需审核退款申请,根据情况决定是否同意退款;若同意,需进行退款操作。 + +9. 退款成功 +说明:商家或平台已同意退款申请,并完成退款操作,款项已返还给用户。 +操作:订单流程结束,可记录退款相关信息。 + +10. 退款失败 +说明:退款申请因各种原因未能成功处理,如支付渠道问题、用户账户异常等。 +操作:商家或平台需与用户沟通,解决问题后重新发起退款操作。 +状态流转图示例 + +注意:(括号中的为订单状态),发起支付、用户支付中等为处理逻辑 +(待支付) ── 发起支付 ── 用户支付中 ── 支付回调成功或者主动查询支付成功状态 ──> (支付成功) ── 排队中 ──> (设备执行中)── 飞机拍照 ── 飞机返航 ──> (素材上传中) ──> (素材上传完成) ── 用户下载 ──> (用户下载完成) + └─ 长时间未支付自动取消 ──> (已取消) + └─ 退款 ──> (退款中) ── 同意 ──> (退款成功) + └─ 拒绝并填写原因 ──> (退款失败) diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/CommonStatus.java b/zlt-business/order-center/src/main/java/com/central/order/enums/CommonStatus.java new file mode 100644 index 00000000..12951cf5 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/CommonStatus.java @@ -0,0 +1,24 @@ +package com.central.order.enums; + +import com.central.common.enums.ZltEnum; +import lombok.Getter; + +/** + * 数据状态枚举类型 + * + * @author lsl create by 2025/1/10 + */ +@Getter +public enum CommonStatus implements ZltEnum { + ENABLE(0,"启用"), + UNABLE(1, "未启用"); + + CommonStatus(Integer id, String content) { + this.id = id; + this.content = content; + } + + private Integer id; + private String content; + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/FileType.java b/zlt-business/order-center/src/main/java/com/central/order/enums/FileType.java new file mode 100644 index 00000000..c93dd7fe --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/FileType.java @@ -0,0 +1,41 @@ +package com.central.order.enums; + +public enum FileType { + JPEG("image/jpeg", ".jpeg", ".jpg"), + PNG("image/png", ".png"), + GIF("image/gif", ".gif"), + MP4("video/mp4", ".mp4"); + + private final String contentType; + private final String[] extensions; + + FileType(String contentType, String... extensions) { + this.contentType = contentType; + this.extensions = extensions; + } + + public String getContentType() { + return contentType; + } + + public String[] getExtensions() { + return extensions; + } + + /** + * 根据文件扩展名获取对应的 FileType + * + * @param extension 文件扩展名 + * @return 对应的 FileType,如果不支持则返回 null + */ + public static FileType fromExtension(String extension) { + for (FileType type : values()) { + for (String ext : type.getExtensions()) { + if (ext.equalsIgnoreCase(extension)) { + return type; + } + } + } + return null; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/HomeCarouselType.java b/zlt-business/order-center/src/main/java/com/central/order/enums/HomeCarouselType.java new file mode 100644 index 00000000..bc5c2e57 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/HomeCarouselType.java @@ -0,0 +1,26 @@ +package com.central.order.enums; + +import com.central.common.enums.ZltEnum; +import lombok.Getter; + +/** + * 轮播类型枚举类型 + * + * @author lsl create by 2025/2/19 + */ +@Getter +public enum HomeCarouselType implements ZltEnum { + HOME(0,"首页轮播"), + ACTIVITY(1, "活动"), + SHOOTING_ANGLE(2,"拍照角度"), + GUIDANCE(3,"引导"), + BIG_PICTURE(4,"大图"); + + private Integer id; + private String content; + + HomeCarouselType(Integer i, String content) { + this.id = i; + this.content = content; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/MessageTemplateEnum.java b/zlt-business/order-center/src/main/java/com/central/order/enums/MessageTemplateEnum.java new file mode 100644 index 00000000..47ab6ce9 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/MessageTemplateEnum.java @@ -0,0 +1,67 @@ +package com.central.order.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum MessageTemplateEnum { + // 基础订单状态 + ORDER_CREATED(1, "新订单提醒", "您有一个新的订单 #{orderNo} 已创建"), + ORDER_PAID(2, "支付成功提醒", "订单 #{orderNo} 已支付成功,正在排队中"), + ORDER_CANCELLED(3, "订单取消提醒", "订单 #{orderNo} 已取消"), + + // 服务状态 + SERVICE_START(4, "服务开始提醒", "订单 #{orderNo} 已开始服务"), + SERVICE_COMPLETE(5, "服务完成提醒", "订单 #{orderNo} 服务已完成"), + + // 素材上传状态 + MATERIAL_UPLOADING(6, "素材上传提醒", "订单 #{orderNo} 正在上传素材"), + MATERIAL_UPLOADED(7, "素材上传完成提醒", "订单 #{orderNo} 素材已上传完成"), + + // 退款相关状态 + REFUND_APPLYING(8, "退款申请提醒", "订单 #{orderNo} 正在申请退款"), + REFUND_SUCCESS(9, "退款成功提醒", "订单 #{orderNo} 已退款成功"), + REFUND_FAILED(10, "退款失败提醒", "订单 #{orderNo} 退款失败"), + REFUND_RETRYING(11, "重新退款提醒", "订单 #{orderNo} 正在重新申请退款"); + + private final Integer type; + private final String title; + private final String contentTemplate; + + public static MessageTemplateEnum getByOrderStatus(Integer orderStatus) { + if (orderStatus == null) { + return null; + } + + switch (orderStatus) { + case 0: return ORDER_CREATED; // 待支付 + case 1: return ORDER_PAID; // 已支付排队中 + case 2: return ORDER_CANCELLED; // 已取消 + case 3: return SERVICE_COMPLETE; // 设备执行完成 + case 4: return SERVICE_START; // 正在服务中 + case 5: return MATERIAL_UPLOADING; // 素材上传中 + case 6: return MATERIAL_UPLOADED; // 素材上传完成 + case 7: return REFUND_APPLYING; // 退款中 + case 8: return REFUND_SUCCESS; // 已退款 + case 9: return REFUND_FAILED; // 退款失败 + default: return null; + } + } + + /** + * 根据状态变更获取消息模板 + */ + public static MessageTemplateEnum getByStatusChange(Integer oldStatus, Integer newStatus) { + if (oldStatus == null || newStatus == null) { + return getByOrderStatus(newStatus); + } + + // 特殊状态变更处理 + if (oldStatus == 9 && newStatus == 7) { // 从退款失败到退款中 + return REFUND_RETRYING; + } + + return getByOrderStatus(newStatus); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/OrderStatus.java b/zlt-business/order-center/src/main/java/com/central/order/enums/OrderStatus.java new file mode 100644 index 00000000..a34dfedd --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/OrderStatus.java @@ -0,0 +1,86 @@ +package com.central.order.enums; + +import com.central.common.enums.ZltEnum; +import lombok.Getter; +/** + * 订单状态枚举类型 + * + * @author lsl create by 2025/1/10 + */ +@Getter +public enum OrderStatus implements ZltEnum { + UNPAID(0,"待支付"), + PAID(1, "已支付排队中"), + CANCELED(2, "已取消"), + DOING(4,"正在服务中"), + COMPLETE(3,"设备执行完成"), + UPLOADING(5,"素材上传中"), + UPLOADED(6,"素材上传完成(任务完成)"), + REFUNDING(7,"退款中"), + REFUNDED(8,"已退款"), + REFUND_FAILED(9,"退款失败"); + + OrderStatus(Integer id, String content) { + this.id = id; + this.content = content; + } + + private Integer id; + private String content; + + /** + * 判断订单状态是否允许编辑视频 + * 只有设备执行完成的订单才能进行视频编辑 + */ + public static boolean isValidForEdit(Integer status) { + return status != null && status.equals(COMPLETE.getId()); + } + + /** + * 根据ID获取状态枚举 + */ + public static OrderStatus fromId(Integer id) { + if (id == null) { + return null; + } + for (OrderStatus status : values()) { + if (status.getId().equals(id)) { + return status; + } + } + return null; + } + + /** + * 获取状态描述 + */ + public static String getDesc(Integer id) { + OrderStatus status = fromId(id); + return status != null ? status.getContent() : "未知状态"; + } + + /** + * 判断是否为最终状态 + */ + public static boolean isFinalStatus(Integer status) { + return status != null && ( + status.equals(CANCELED.getId()) || + status.equals(UPLOADED.getId()) || + status.equals(REFUNDED.getId()) || + status.equals(REFUND_FAILED.getId()) + ); + } + + /** + * 判断是否可以退款 + */ + public static boolean canRefund(Integer status) { + return status != null && ( + status.equals(PAID.getId()) || + status.equals(DOING.getId()) || + status.equals(COMPLETE.getId()) || + status.equals(UPLOADING.getId()) || + status.equals(UPLOADED.getId()) + ); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/OrderStatusChangeEnum.java b/zlt-business/order-center/src/main/java/com/central/order/enums/OrderStatusChangeEnum.java new file mode 100644 index 00000000..66095bca --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/OrderStatusChangeEnum.java @@ -0,0 +1,64 @@ +package com.central.order.enums; + +import lombok.Getter; + +@Getter +public enum OrderStatusChangeEnum { + // 支付相关 + PAID(OrderStatus.UNPAID.getId(), OrderStatus.PAID.getId(), + "订单支付成功通知", "您的订单 #{orderNo} 已支付成功,正在排队中"), + + // 取消相关 + CANCELED(null, OrderStatus.CANCELED.getId(), + "订单取消通知", "您的订单 #{orderNo} 已取消"), + + // 服务状态相关 + SERVICE_START(OrderStatus.PAID.getId(), OrderStatus.DOING.getId(), + "服务开始通知", "您的订单 #{orderNo} 已开始服务"), + SERVICE_COMPLETE(OrderStatus.DOING.getId(), OrderStatus.COMPLETE.getId(), + "服务完成通知", "您的订单 #{orderNo} 服务已完成"), + + // 素材上传相关 + UPLOADING(OrderStatus.DOING.getId(), OrderStatus.UPLOADING.getId(), + "素材上传通知", "您的订单 #{orderNo} 正在上传素材"), + UPLOADED(OrderStatus.UPLOADING.getId(), OrderStatus.COMPLETE.getId(), + "素材上传完成通知", "您的订单 #{orderNo} 素材已上传完成"), + + // 退款相关 + REFUNDING(null, OrderStatus.REFUNDING.getId(), + "退款申请通知", "您的订单 #{orderNo} 正在申请退款"), + REFUND_SUCCESS(OrderStatus.REFUNDING.getId(), OrderStatus.REFUNDED.getId(), + "退款成功通知", "您的订单 #{orderNo} 已退款成功"), + REFUND_FAILED(OrderStatus.REFUNDING.getId(), OrderStatus.REFUND_FAILED.getId(), + "退款失败通知", "您的订单 #{orderNo} 退款失败"), + RETRY_REFUND(OrderStatus.REFUND_FAILED.getId(), OrderStatus.REFUNDING.getId(), + "重新退款通知", "您的订单 #{orderNo} 正在重新申请退款"); + + private final Integer oldStatus; + private final Integer newStatus; + private final String title; + private final String contentTemplate; + + OrderStatusChangeEnum(Integer oldStatus, Integer newStatus, String title, String contentTemplate) { + this.oldStatus = oldStatus; + this.newStatus = newStatus; + this.title = title; + this.contentTemplate = contentTemplate; + } + + public static OrderStatusChangeEnum getByStatusChange(Integer oldStatus, Integer newStatus) { + for (OrderStatusChangeEnum changeEnum : values()) { + // 如果oldStatus为null,则只匹配newStatus + if (changeEnum.oldStatus == null) { + if (changeEnum.newStatus.equals(newStatus)) { + return changeEnum; + } + } + // 否则匹配两个状态 + else if (changeEnum.oldStatus.equals(oldStatus) && changeEnum.newStatus.equals(newStatus)) { + return changeEnum; + } + } + return null; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/PayeeTypeEnum.java b/zlt-business/order-center/src/main/java/com/central/order/enums/PayeeTypeEnum.java new file mode 100644 index 00000000..49422bf5 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/PayeeTypeEnum.java @@ -0,0 +1,26 @@ +package com.central.order.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum PayeeTypeEnum { + MERCHANT_ID("MERCHANT_ID", "商户ID"), + PERSONAL_OPENID("PERSONAL_OPENID", "个人openid"); + + private final String code; + private final String desc; + + public static String getDesc(String code) { + if (code == null) { + return ""; + } + for (PayeeTypeEnum type : values()) { + if (type.getCode().equals(code)) { + return type.getDesc(); + } + } + return "未知类型"; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/ProfitSharingStatusEnum.java b/zlt-business/order-center/src/main/java/com/central/order/enums/ProfitSharingStatusEnum.java new file mode 100644 index 00000000..9236730b --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/ProfitSharingStatusEnum.java @@ -0,0 +1,28 @@ +package com.central.order.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum ProfitSharingStatusEnum { + INIT(0, "待分账"), + PROCESSING(1, "分账中"), + SUCCESS(2, "分账成功"), + FAILED(3, "分账失败"); + + private final int code; + private final String desc; + + public static String getDesc(Integer code) { + if (code == null) { + return ""; + } + for (ProfitSharingStatusEnum status : values()) { + if (status.getCode() == code) { + return status.getDesc(); + } + } + return "未知状态"; + } +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/QrcodeStatus.java b/zlt-business/order-center/src/main/java/com/central/order/enums/QrcodeStatus.java new file mode 100644 index 00000000..f766d984 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/QrcodeStatus.java @@ -0,0 +1,4 @@ +package com.central.order.enums; + +public enum QrcodeStatus { +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/enums/RefundState.java b/zlt-business/order-center/src/main/java/com/central/order/enums/RefundState.java new file mode 100644 index 00000000..0fb44523 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/enums/RefundState.java @@ -0,0 +1,26 @@ +package com.central.order.enums; + +import com.central.common.enums.ZltEnum; +import lombok.Getter; + +/** + * 订单状态枚举类型 + * + * @author lsl create by 2025/1/10 + */ +@Getter +public enum RefundState implements ZltEnum { + APPROVING(0,"审核中"), + APPROVED(1, "已通过"), + REFUSED(2,"已拒绝"); + + + RefundState(Integer id, String content) { + this.id = id; + this.content = content; + } + + private Integer id; + private String content; + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/event/OrderStatusChangeEvent.java b/zlt-business/order-center/src/main/java/com/central/order/event/OrderStatusChangeEvent.java new file mode 100644 index 00000000..d10280d9 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/event/OrderStatusChangeEvent.java @@ -0,0 +1,23 @@ +package com.central.order.event; + +import lombok.Getter; +import org.springframework.context.ApplicationEvent; + +@Getter +public class OrderStatusChangeEvent extends ApplicationEvent { + private String orderNo; + private Integer oldStatus; + private Integer newStatus; + private Long userId; + private String orderInfo; + + public OrderStatusChangeEvent(Object source, String orderNo, Integer oldStatus, + Integer newStatus, Long userId, String orderInfo) { + super(source); + this.orderNo = orderNo; + this.oldStatus = oldStatus; + this.newStatus = newStatus; + this.userId = userId; + this.orderInfo = orderInfo; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/DeviceCenterService.java b/zlt-business/order-center/src/main/java/com/central/order/feign/DeviceCenterService.java new file mode 100644 index 00000000..c70bef6f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/DeviceCenterService.java @@ -0,0 +1,33 @@ +package com.central.order.feign; + +import com.alibaba.fastjson.JSONObject; +import com.central.common.constant.ServiceNameConstants; +import com.central.order.feign.fallback.DeviceCenterServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * device-center模块远程调用 + * + * @author lsl + * @version 1.0 + * @description user-center模块远程调用 + * @create 2025/1/13 + **/ +@FeignClient(name = ServiceNameConstants.DEVICE_SERVICE, fallbackFactory = DeviceCenterServiceFallbackFactory.class, dismiss404 = true) +public interface DeviceCenterService { + + /** + * 通过ID查询文件sign + * + * @param id 文件ID + * @return + */ + @GetMapping("/wayline/sign/{id}") + String getLineFileSign(@PathVariable("id") String id); + + @GetMapping("/live/stream-urls") + JSONObject getStreamUrls(@RequestParam("deviceId") String deviceId) ; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/FileCenterService.java b/zlt-business/order-center/src/main/java/com/central/order/feign/FileCenterService.java new file mode 100644 index 00000000..8afc0f57 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/FileCenterService.java @@ -0,0 +1,50 @@ +package com.central.order.feign; + +import com.central.common.constant.ServiceNameConstants; +import com.central.common.model.FileInfo; +import com.central.common.model.Result; +import com.central.order.feign.fallback.FileCenterServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +/** + * user-center模块远程调用 + * + * @author lsl + * @version 1.0 + * @description user-center模块远程调用 + * @create 2025/1/13 + **/ +@FeignClient(name = ServiceNameConstants.FILE_SERVICE, fallbackFactory = FileCenterServiceFallbackFactory.class, dismiss404 = true) +public interface FileCenterService { + + /** + * 通过ID查询预览地址 + * + * @param id 文件ID + * @return + */ + @GetMapping("/file/{id}") + String getFileViewUrl(@PathVariable("id") String id); + + @GetMapping("/type/{id}") + String getFileContentType(@PathVariable("id") String id); + + @GetMapping("/qrcode/{codeId}") + Result uploadQrCodeFile(@PathVariable("codeId") String codeId) throws Exception; + + @PostMapping("/path") + FileInfo creatFileInfo(@RequestBody String path); + + @GetMapping("/files/path") + String getViewUrlByPath(@RequestParam("path") String path) ; + + @GetMapping("/files/path/style") + String getViewUrlByPathStyle(@RequestParam("params") Map params) ; + + @GetMapping("/list/files") + List getListFiles(@RequestParam("prefix") String prefix) ; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/UserCenterService.java b/zlt-business/order-center/src/main/java/com/central/order/feign/UserCenterService.java new file mode 100644 index 00000000..246ad679 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/UserCenterService.java @@ -0,0 +1,29 @@ +package com.central.order.feign; + +import com.central.common.constant.ServiceNameConstants; +import com.central.common.model.SysUser; +import com.central.order.feign.fallback.UserCenterServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +/** + * user-center模块远程调用 + * + * @author lsl + * @version 1.0 + * @description user-center模块远程调用 + * @create 2025/1/13 + **/ +@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserCenterServiceFallbackFactory.class, dismiss404 = true) +public interface UserCenterService { + + /** + * 通过ID查询用户信息 + * + * @param id 用户ID + * @return + */ + @GetMapping("/users/{id}") + SysUser findUserById(@PathVariable("id") Long id); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java new file mode 100644 index 00000000..3f7be7de --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java @@ -0,0 +1,36 @@ +package com.central.order.feign.fallback; + +import com.alibaba.fastjson.JSONObject; +import com.central.order.feign.DeviceCenterService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +/** + * 文件中心调用失败回调 + * + * @author lsl + * @version 1.0 + * @description 设备中心调用失败回调 + * @create 2025/1/17 11:33 + **/ +@Slf4j +@Component +public class DeviceCenterServiceFallbackFactory implements FallbackFactory { + + @Override + public DeviceCenterService create(Throwable cause) { + return new DeviceCenterService() { + + @Override + public String getLineFileSign(String id) { + return ""; + } + + @Override + public JSONObject getStreamUrls(String deviceId) { + return null; + } + }; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java new file mode 100644 index 00000000..03b6253a --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java @@ -0,0 +1,66 @@ +package com.central.order.feign.fallback; + +import com.central.common.model.FileInfo; +import com.central.common.model.Result; +import com.central.order.feign.FileCenterService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; + +/** + * 文件中心调用失败回调 + * + * @author lsl + * @version 1.0 + * @description 用户中心调用失败回调 + * @create 2025/1/17 11:33 + **/ +@Slf4j +@Component +public class FileCenterServiceFallbackFactory implements FallbackFactory { + + @Override + public FileCenterService create(Throwable cause) { + return new FileCenterService() { + + @Override + public String getFileViewUrl(String id) { + return ""; + } + + @Override + public String getFileContentType(String id) { + return ""; + } + + @Override + public Result uploadQrCodeFile(String codeId) throws Exception { + return null; + } + + @Override + public FileInfo creatFileInfo(String path) { + return null; + } + + @Override + public String getViewUrlByPath(String path) { + return ""; + } + + @Override + public String getViewUrlByPathStyle(Map params) { + return ""; + } + + @Override + public List getListFiles(String prefix) { + return List.of(); + } + + }; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/UserCenterServiceFallbackFactory.java b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/UserCenterServiceFallbackFactory.java new file mode 100644 index 00000000..ed4a98a1 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/feign/fallback/UserCenterServiceFallbackFactory.java @@ -0,0 +1,31 @@ +package com.central.order.feign.fallback; + +import com.central.common.model.SysUser; +import com.central.order.feign.UserCenterService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +/** + * 用户中心调用失败回调 + * + * @author caiji + * @version 1.0 + * @description 用户中心调用失败回调 + * @create 2024/8/6 11:33 + **/ +@Slf4j +@Component +public class UserCenterServiceFallbackFactory implements FallbackFactory { + + @Override + public UserCenterService create(Throwable cause) { + return new UserCenterService() { + + @Override + public SysUser findUserById(Long id) { + return null; + } + }; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/handler/WxMessageHandler.java b/zlt-business/order-center/src/main/java/com/central/order/handler/WxMessageHandler.java new file mode 100644 index 00000000..b7199fdb --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/handler/WxMessageHandler.java @@ -0,0 +1,134 @@ +package com.central.order.handler; + +import com.central.order.model.WxMessageRecord; +import com.central.order.model.WxUserSubscribe; +import com.central.order.service.IWxTemplateMessageService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import me.chanjar.weixin.common.api.WxConsts; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; +import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; + +@Slf4j +@Component +@RequiredArgsConstructor +public class WxMessageHandler { + + private final WxMpService wxMpService; + private final IWxTemplateMessageService templateMessageService; + + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage) { + try { + String msgType = wxMessage.getMsgType(); + if (WxConsts.XmlMsgType.EVENT.equals(msgType)) { + return handleEventMessage(wxMessage); + } + return null; + } catch (Exception e) { + log.error("处理微信消息失败", e); + return null; + } + } + + private WxMpXmlOutMessage handleEventMessage(WxMpXmlMessage wxMessage) { + String event = wxMessage.getEvent(); + switch (event) { + case WxConsts.EventType.TEMPLATE_SEND_JOB_FINISH: + return handleTemplateSendJobFinish(wxMessage); + case WxConsts.EventType.SUBSCRIBE: + return handleSubscribeEvent(wxMessage); + case WxConsts.EventType.UNSUBSCRIBE: + return handleUnsubscribeEvent(wxMessage); + default: + log.info("未处理的事件类型:{}", event); + return null; + } + } + + /** + * 处理模板消息发送完成事件 + */ + private WxMpXmlOutMessage handleTemplateSendJobFinish(WxMpXmlMessage wxMessage) { + try { + String openId = wxMessage.getFromUser(); + String msgId = wxMessage.getMsgId().toString(); + String status = wxMessage.getStatus(); + + log.info("模板消息发送结果:openId={}, msgId={}, status={}", + openId, msgId, status); + + // 更新消息发送状态 + updateMessageStatus(openId, msgId, status.equals("SUCCESS")?1:0); + + } catch (Exception e) { + log.error("处理模板消息发送结果事件失败", e); + } + return null; + } + + private WxMpXmlOutMessage handleSubscribeEvent(WxMpXmlMessage wxMessage) { + String openId = wxMessage.getFromUser(); + log.info("用户关注:openId={}", openId); + + // 保存用户关注状态 + saveUserSubscribeStatus(openId, true); + + return WxMpXmlOutMessage.TEXT() + .content("感谢关注!") + .fromUser(wxMessage.getToUser()) + .toUser(openId) + .build(); + } + + private WxMpXmlOutMessage handleUnsubscribeEvent(WxMpXmlMessage wxMessage) { + String openId = wxMessage.getFromUser(); + log.info("用户取消关注:openId={}", openId); + + // 更新用户关注状态 + saveUserSubscribeStatus(openId, false); + + return null; + } + + /** + * 更新消息发送状态 + */ + private void updateMessageStatus(String openId, String msgId, Integer status) { + try { + WxMessageRecord record = WxMessageRecord.builder() + .openId(openId) + .msgId(msgId) + .status(status) + .build(); + + // TODO: 调用消息记录服务更新状态 + // messageRecordService.updateStatus(record); + + } catch (Exception e) { + log.error("更新消息状态失败:openId={}, msgId={}", openId, msgId, e); + } + } + + /** + * 保存用户关注状态 + */ + private void saveUserSubscribeStatus(String openId, boolean isSubscribe) { + try { + WxUserSubscribe userSubscribe = WxUserSubscribe.builder() + .openId(openId) + .subscribed(isSubscribe) + .updateTime(LocalDateTime.now()) + .build(); + + // TODO: 调用用户服务更新关注状态 + // userSubscribeService.updateStatus(userSubscribe); + + } catch (Exception e) { + log.error("更新用户关注状态失败:openId={}", openId, e); + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java b/zlt-business/order-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java new file mode 100644 index 00000000..939b326c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java @@ -0,0 +1,258 @@ +package com.central.order.listener; + +import com.alibaba.fastjson.JSON; +import com.central.common.model.SysUser; +import com.central.order.constants.EditTaskStatus; +import com.central.order.enums.MessageTemplateEnum; +import com.central.order.enums.OrderStatus; +import com.central.order.enums.OrderStatusChangeEnum; +import com.central.order.event.OrderStatusChangeEvent; +import com.central.order.feign.UserCenterService; +import com.central.order.model.*; +import com.central.order.service.*; +import com.central.order.util.DateUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Slf4j +@Component +@RequiredArgsConstructor +public class OrderStatusChangeListener { + + @Autowired + private IMessageService messageService; + @Autowired + private ITourismService tourismService; + @Autowired + private IOrderService orderService; + @Autowired + private IQrCodeService qrCodeService; + @Autowired + private IVideoEditService videoEditService; + @Autowired + private IOrderFileService orderFileService; + @Autowired + private IWxTemplateMessageService wxTemplateMessageService; + @Autowired + private UserCenterService userCenterService; + @Autowired + private IEditTaskService editTaskService; + @Autowired + private WxMiniSubscribeService wxMiniSubscribeService; + + @EventListener + @Async + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void handleOrderStatusChange(OrderStatusChangeEvent event) { + try { + log.info("开始处理订单状态变更事件: orderId={}, oldStatus={}, newStatus={}", + event.getOrderNo(), event.getOldStatus(), event.getNewStatus()); + + // 参数校验 + if (event.getOrderNo() == null) { + log.error("订单号为空,无法处理状态变更事件"); + return; + } + + // 获取状态变更类型 + OrderStatusChangeEnum changeEnum = OrderStatusChangeEnum + .getByStatusChange(event.getOldStatus(), event.getNewStatus()); + + if (changeEnum == null) { + log.warn("未找到对应的状态变更类型: oldStatus={}, newStatus={}", + event.getOldStatus(), event.getNewStatus()); + return; + } + + // 获取订单信息 + Order order = orderService.getOrderByNumber(event.getOrderNo()); + if (order == null) { + log.error("未找到订单信息: orderId={}", event.getOrderNo()); + return; + } + + // 获取景区信息 + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + if (tourism == null) { + log.error("未找到景区信息: tourismId={}", order.getTourismId()); + return; + } + + // 处理支付成功状态 + if (isPaymentSuccess(event.getOldStatus(), event.getNewStatus())) { + handlePaymentSuccess(order, tourism); + } + + // 构建消息内容 + String content = changeEnum.getContentTemplate() + .replace("#{orderNo}", event.getOrderNo()) + + "\n景区名称:" + tourism.getTourismName() + + "\n" + event.getOrderInfo(); + + // 获取消息模板 + MessageTemplateEnum template = MessageTemplateEnum.getByStatusChange(event.getOldStatus(), event.getNewStatus()); + if (template == null) { + log.warn("未找到对应的消息模板: oldStatus={}, newStatus={}", + event.getOldStatus(), event.getNewStatus()); + return; + } + + // 创建站内信 + Message message = new Message(); + message.setTitle(changeEnum.getTitle()); + message.setContent(content); + message.setType(template.getType()); // 使用模板中的类型 + message.setUserId(event.getUserId()); + message.setRelatedId(event.getOrderNo()); + + // 设置额外信息 + Map extra = new HashMap<>(); + extra.put("oldStatus", event.getOldStatus()); + extra.put("newStatus", event.getNewStatus()); + extra.put("tourismId", order.getTourismId()); + extra.put("tourismName", tourism.getTourismName()); + + message.setExtra(JSON.toJSONString(extra)); // Fastjson不会抛出受检异常 + + log.info("准备保存站内信: title={}, userId={}, content={}", + message.getTitle(), message.getUserId(), message.getContent()); + + // 保存消息 + messageService.createMessage(message); + + log.info("站内信创建成功: userId={}", message.getUserId()); + + // 订单完成时,检查是否需要触发一键成片 + if (OrderStatus.COMPLETE.getId().equals(event.getNewStatus())) { + handleOrderComplete(order); + } + + } catch (Exception e) { + log.error("处理订单状态变更事件失败", e); + throw new RuntimeException("处理订单状态变更事件失败", e); + } + } + + /** + * 判断是否为支付成功状态变更 + */ + private boolean isPaymentSuccess(Integer oldStatus, Integer newStatus) { + return OrderStatus.UNPAID.getId() + .equals(oldStatus) && OrderStatus.PAID.getId().equals(newStatus); + } + + /** + * 处理支付成功逻辑 + */ + + private void handlePaymentSuccess(Order order, Tourism tourism) { + try { + // 1. 发送微信通知 + + SysUser sysUser = userCenterService.findUserById(order.getUserId()); + // 2. 查询订单排队信息 + Integer queue = orderService.getOrderRankingByOrderId(order.getId(),tourism.getId()); + + // 发送小程序订阅消息 + if (sysUser.getOpenId() != null) { + String tip = "支付成功,当前排第"+queue+"位"; + String orderName = tourism.getTourismName(); + String pageUrl = "pages/task/task"; + wxMiniSubscribeService.sendServiceProcessMsg( + sysUser.getOpenId(), + orderName, + tip, + order.getOrderNo(), + DateUtils.sdf.format(order.getPayTime()), + "", + pageUrl + ); + } + + // 2. 记录支付成功日志 + log.info("订单支付成功: orderNo={}, amount={}, tourismName={}", + order.getOrderNo(), order.getOrderAmount(), tourism.getTourismName()); + + } catch (Exception e) { + // 通知失败不影响主流程 + log.error("处理支付成功通知失败: orderNo={}", order.getOrderNo(), e); + } + } + + /** + * 处理订单完成逻辑 + */ + private void handleOrderComplete(Order order) { + try { + // 1. 检查是否开启一键成片 + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (!isVideoEditEnabled(qrCode)) { + log.info("未开启一键成片功能: orderNo={}, codeId={}", + order.getOrderNo(), order.getCodeId()); + return; + } + + // 3. 创建新任务 + EditTask task = editTaskService.createTask(order.getOrderNo(), order.getUserId()); + + // 4. 获取素材文件 + List orderFiles = orderFileService.getOrderFileByOrderNo(order.getOrderNo()); + + // 5. 提交编辑任务 + String jobId = videoEditService.submitEditTask(order.getOrderNo(), orderFiles); + log.info("提交一键成片任务成功: orderNo={}, jobId={}, totalMediaFiles={}", + order.getOrderNo(), jobId, orderFiles.size()); + + // 6. 更新任务信息 + task.setJobId(jobId); + task.setStatus(EditTaskStatus.PROCESSING); + editTaskService.saveOrUpdateTask(task); + + // 新增:查找下一个排队用户 + Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId()); + if (nextOrder != null) { + SysUser nextUser = userCenterService.findUserById(nextOrder.getUserId()); + Tourism tourism = tourismService.getTourismById(nextOrder.getTourismId()); + if (nextUser != null && nextUser.getOpenId() != null && tourism != null) { + String activityName = tourism.getTourismName(); // 活动名称 + String remark = "即将为您进行拍摄服务"; + String activityNo = nextOrder.getOrderNo(); // 活动编号 + String pageUrl = "pages/task/task"; + wxMiniSubscribeService.sendServiceProcessMsg( + nextUser.getOpenId(), + activityName, + remark, + activityNo, + DateUtils.sdf.format(nextOrder.getPayTime()), + "", + pageUrl + ); + log.info("已通知下一个排队用户: userId={}, openId={}, orderNo={}", nextUser.getId(), nextUser.getOpenId(), activityNo); + } + } + + } catch (Exception e) { + log.error("触发一键成片或排队通知失败: orderNo={}", order.getOrderNo(), e); + } + } + + /** + * 检查是否开启一键成片功能 + */ + private boolean isVideoEditEnabled(QrCode qrCode) { + return qrCode != null + && qrCode.getEnableVideoEdit() != null + && qrCode.getEnableVideoEdit() == 1 + && qrCode.getTemplateId() != null; // 确保有模板ID + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/DashboardMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/DashboardMapper.java new file mode 100644 index 00000000..ccee4a92 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/DashboardMapper.java @@ -0,0 +1,91 @@ +package com.central.order.mapper; + +import com.central.order.model.vo.IncomeDataVO; +import com.central.order.model.vo.TourismRankingVO; +import com.central.order.model.vo.TrendDataVO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +@Mapper +public interface DashboardMapper { + + @Select("SELECT COUNT(*) FROM orders WHERE is_del = 0") + Long getTotalOrders(); + + @Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = CURDATE()") + Long getTodayOrders(); + + @Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)") + Long getYesterdayOrders(); + + @Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND order_status = #{completeStatus}") + Long getCompletedOrders(); + + @Select({ + "" + }) + Long getTotalIncome(); + + @Select({ + "" + }) + Long getTodayIncome(); + + + + @Select({ + "SELECT", + " DATE_FORMAT(create_time, '%Y-%m-%d') as date,", + " 'orders' as type,", + " COUNT(*) as value", + "FROM orders", + "WHERE is_del = 0", + " AND create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)", + "GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')" + }) + List getOrderTrend(); + + @Select({ + "SELECT", + " 'platform' as type,", + " SUM(platform_amount) as value", + "FROM order_statistics", + "WHERE DATE(create_time) = CURDATE()", + "UNION ALL", + "SELECT", + " 'tourism' as type,", + " SUM(tourism_amount) as value", + "FROM order_statistics", + "WHERE DATE(create_time) = CURDATE()" + }) + List getIncomeData(); + + @Select({ + "SELECT", + " t.id,", + " t.tourism_name as name,", + " COUNT(o.id) as value", + "FROM tourisms t", + "LEFT JOIN orders o ON t.id = o.tourism_id", + "WHERE t.is_del = 0", + " AND o.is_del = 0", + " AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)", + "GROUP BY t.id, t.tourism_name", + "ORDER BY value DESC", + "LIMIT 10" + }) + List getTourismRanking(); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/EditTaskMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/EditTaskMapper.java new file mode 100644 index 00000000..e4bf409c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/EditTaskMapper.java @@ -0,0 +1,12 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.EditTask; +import org.apache.ibatis.annotations.Mapper; + +/** + * 视频编辑任务Mapper接口 + */ +@Mapper +public interface EditTaskMapper extends BaseMapper { +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/HomeCarouselMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/HomeCarouselMapper.java new file mode 100644 index 00000000..82af46dd --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/HomeCarouselMapper.java @@ -0,0 +1,29 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.HomeCarousel; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * HomeCarousel information + * + * @author lsl + * @date 2025-2-19 17:52:54 + */ +@Mapper +public interface HomeCarouselMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/MessageMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/MessageMapper.java new file mode 100644 index 00000000..9553ab6f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/MessageMapper.java @@ -0,0 +1,77 @@ +package com.central.order.mapper; + + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.Message; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Update; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Mapper +public interface MessageMapper extends SuperMapper { + + List findList(Page page, + @Param("tenantId") String tenantId); + + @Update("UPDATE sys_message SET status = 1, read_time = #{readTime} " + + "WHERE id = #{id}") + int markAsRead(@Param("id") Long id, + @Param("readTime") Date readTime); + + @Update("UPDATE sys_message SET status = 1, read_time = #{readTime} " + + "WHERE status = 0") + int markAllAsRead( @Param("readTime") Date readTime); + + /** + * 查询消息列表 + * 使用@Param注解明确指定参数名 + */ + List findList(Page page, + @Param("userId") Long userId, + @Param("tenantId") String tenantId, + @Param("params") Map params); + + /** + * 批量插入消息 + */ + int batchInsert(@Param("list") List messages); + + /** + * 批量更新消息状态 + */ + int batchUpdateStatus(@Param("ids") List ids, + @Param("status") Integer status, + @Param("readTime") Date readTime, + @Param("userId") Long userId); + + /** + * 获取未读消息数量 + */ + int getUnreadCount(@Param("userId") Long userId, + @Param("tenantId") String tenantId); + + /** + * 按类型获取未读消息数量 + */ + List> getUnreadCountByType(@Param("userId") Long userId, + @Param("tenantId") String tenantId); + + /** + * 删除指定时间之前的已读消息 + */ + int deleteReadMessages(@Param("beforeTime") Date beforeTime, + @Param("userId") Long userId, + @Param("tenantId") String tenantId); + + /** + * 根据关联ID查询消息 + */ + List findByRelatedId(@Param("relatedId") String relatedId, + @Param("userId") Long userId, + @Param("tenantId") String tenantId); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderFileMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderFileMapper.java new file mode 100644 index 00000000..715a2844 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderFileMapper.java @@ -0,0 +1,49 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.OrderFile; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +/** + * Order File information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface OrderFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("params") Map params); + + + // 新增订单资源 + int insertOrderFile(OrderFile orderFile); + // 根据订单编号查询文件资源信息 + List getOrderFileByOrderNo(@Param("orderNo") String orderNo); + + List getOrderFileByOrderNoAndFileType(@Param("orderNo") String orderNo, @Param("fileType") String contentType); + // 文件ID查询文件 + OrderFile getFileByFileId(@Param("fileId") String fileId); + // 查询所有处于排队状态的订单,用于后续按顺序处理(可根据业务需求添加排序等逻辑) + List getOrderFilesByUserId(@Param("userId") Long userId); + + List findListByUser(Page page, @Param("p") Map params); + + /** + * 获取订单的视频文件 + */ + @Select("SELECT * FROM order_files WHERE order_no = #{orderNo} AND file_type = 'video/mp4' ORDER BY create_time ASC") + List getOrderVideoFiles(@Param("orderNo") String orderNo); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderMapper.java new file mode 100644 index 00000000..20602ef2 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderMapper.java @@ -0,0 +1,61 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.Order; +import com.central.order.model.OrderRanking; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface OrderMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + // 根据订单状态查询订单列表 + List getOrdersByStatus(@Param("status") Integer status); + // 新增订单 + int insertOrder(Order order); + // 根据订单编号查询订单信息 + Order getOrderById(@Param("orderId") Long orderId); + // 更新订单状态 + int updateOrderStatus(@Param("orderId") Long orderId, @Param("newStatus") Integer newStatus); + // 查询所有处于排队状态的订单,用于后续按顺序处理(可根据业务需求添加排序等逻辑) + List getOrdersInQueue(); + + // 根据店铺编号和创建时间(当天)查询订单数量 + List findByShopIdAndCreateTimeGreaterThanEqualAndCreateTimeLessThanEqual(@Param("tourismId") Long tourismId, @Param("startDate") Date startDate, @Param("endDate") Date endDate); + + // 根据订单编号查询订单信息 + Order getOrderByNumber(@Param("orderNumber") String orderNumber); + + List findListByUser(Page page, @Param("p") Map params); + + @Select("SELECT \n" + + " id,\n" + + " @rank := @rank + 1 as ranking\n" + + "FROM \n" + + " orders,\n" + + " (SELECT @rank := 0) r\n" + + "WHERE \n" + + " order_status in(1,4,5,6) and tourism_id = #{tourismId} \n" + + "ORDER BY \n" + + " pay_time;") + List getOrderRanking1(@Param("tourismId") Long tourismId); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java new file mode 100644 index 00000000..1ca87532 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java @@ -0,0 +1,66 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.OrderStatistics; +import com.central.order.model.OrderStatisticsQuery; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface OrderStatisticsMapper extends BaseMapper { + + @Select({ + "" + }) + List> getOrderStatistics(OrderStatisticsQuery query); + + @Select({ + "" + }) + List> getOrderStatisticsByGroup(OrderStatisticsQuery query); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/PaymentRecordMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/PaymentRecordMapper.java new file mode 100644 index 00000000..ec9df4da --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/PaymentRecordMapper.java @@ -0,0 +1,33 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.PaymentRecord; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface PaymentRecordMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + // 插入支付记录 + int insertPaymentRecord(PaymentRecord paymentRecord); + // 根据支付流水号查询支付记录(用于幂等性判断) + PaymentRecord getPaymentRecordByNumber(@Param("paymentNumber") String paymentNumber); + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/ProfitSharingMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/ProfitSharingMapper.java new file mode 100644 index 00000000..1380b9b3 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/ProfitSharingMapper.java @@ -0,0 +1,43 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.ProfitSharing; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Param; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Mapper +public interface ProfitSharingMapper extends BaseMapper { + // 获取总体统计 + @Select("SELECT " + + "COUNT(*) as total_count, " + + "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as success_count, " + + "SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) as fail_count, " + + "SUM(qrcode_amount) as total_amount " + + "FROM profit_sharing") + Map getTotalStatistics(); + + // 获取每日金额趋势 + @Select("SELECT " + + "DATE_FORMAT(create_time, '%Y-%m-%d') as date, " + + "'DAY' as type, " + + "SUM(qrcode_amount) as amount " + + "FROM profit_sharing " + + "WHERE create_time >= #{startTime} " + + "GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')") + List> getDailyAmountTrend(@Param("startTime") Date startTime); + + // 获取每日成功率 + @Select("SELECT " + + "DATE_FORMAT(create_time, '%Y-%m-%d') as date, " + + "'DAY' as type, " + + "ROUND(SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) as value " + + "FROM profit_sharing " + + "WHERE create_time >= #{startTime} " + + "GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')") + List> getDailySuccessRate(@Param("startTime") Date startTime); +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/QrCodeMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/QrCodeMapper.java new file mode 100644 index 00000000..5c09cb96 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/QrCodeMapper.java @@ -0,0 +1,35 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.QrCode; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Qrcode information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface QrCodeMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + + // 新增二维码资源 + int insertQrCode(QrCode qrCode); + // ID查询 + QrCode getByCodeId(@Param("codeId") String codeId); + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/RefundMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/RefundMapper.java new file mode 100644 index 00000000..e2abf4bb --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/RefundMapper.java @@ -0,0 +1,27 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.Refund; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface RefundMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/TourismFileMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/TourismFileMapper.java new file mode 100644 index 00000000..ebf01fec --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/TourismFileMapper.java @@ -0,0 +1,32 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.TourismFile; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Tourism File information + * + * @author lsl + * @date 2025-2-17 17:52:54 + */ +@Mapper +public interface TourismFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + // ID查询 + List getByTourismId(@Param("tourismId") Long tourismId); + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/TourismMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/TourismMapper.java new file mode 100644 index 00000000..a49b5690 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/TourismMapper.java @@ -0,0 +1,35 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.Tourism; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Tourism information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface TourismMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + + // 新增订单资源 + int insertTourism(Tourism tourism); + // ID查询 + Tourism getTourismById(@Param("id") Long id); + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/VideoTemplateMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/VideoTemplateMapper.java new file mode 100644 index 00000000..b42a34ca --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/VideoTemplateMapper.java @@ -0,0 +1,9 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.VideoTemplate; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface VideoTemplateMapper extends BaseMapper { +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/WxMessageRecordMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/WxMessageRecordMapper.java new file mode 100644 index 00000000..68f3138f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/WxMessageRecordMapper.java @@ -0,0 +1,9 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.WxMessageRecord; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface WxMessageRecordMapper extends BaseMapper { +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/EditTask.java b/zlt-business/order-center/src/main/java/com/central/order/model/EditTask.java new file mode 100644 index 00000000..cf415fee --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/EditTask.java @@ -0,0 +1,38 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.*; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("edit_task") +public class EditTask { + @TableId(type = IdType.AUTO) + private Integer id; + + private Long userId; + private String orderSn; + private String jobId; + private String result; + + @Schema(description = "状态:0-待处理 1-处理中 2-处理完成 3-处理失败") + private Integer status; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + //租户ID + private Long tenantId; + + private String remark; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/HomeCarousel.java b/zlt-business/order-center/src/main/java/com/central/order/model/HomeCarousel.java new file mode 100644 index 00000000..4770e6fb --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/HomeCarousel.java @@ -0,0 +1,47 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * HomeCarousel File information + * + * @author lsl + * @date 2025-2-17 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("home_carousel") +public class HomeCarousel extends SuperEntity { + + private static final long serialVersionUID=1L; + + private String imageUrl; + private String redirectUrl; + private int type; + private Integer status; + + private String title; + private String description; + private int sortOrder; + private Date startTime; + private Date endTime; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + //租户ID + private String tenantId; + private String company; + private Integer isDel; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/Message.java b/zlt-business/order-center/src/main/java/com/central/order/model/Message.java new file mode 100644 index 00000000..89fb85fc --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/Message.java @@ -0,0 +1,58 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.Data; + +import java.util.Date; + +@Data +@TableName("sys_message") +public class Message extends SuperEntity { + private static final long serialVersionUID = 1L; + + /** + * 消息标题 + */ + private String title; + + /** + * 消息内容 + */ + private String content; + + /** + * 消息类型:1-退款订单 2-新增订单 + */ + private Integer type; + + /** + * 消息状态:0-未读 1-已读 + */ + private Integer status; + + /** + * 阅读时间 + */ + private Date readTime; + + /** + * 关联ID + */ + private String relatedId; + + /** + * 额外信息(JSON格式) + */ + private String extra; + + /** + * 接收用户ID + */ + private Long userId; + + /** + * 租户ID + */ + private String tenantId; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/Order.java b/zlt-business/order-center/src/main/java/com/central/order/model/Order.java new file mode 100644 index 00000000..5630f14a --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/Order.java @@ -0,0 +1,58 @@ +package com.central.order.model; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("orders") +public class Order extends SuperEntity { + private static final long serialVersionUID=1L; + + private String orderNo; + private String deviceSn; + + private Long userId; + private Long tourismId; + private transient String tourismName; + private String workspaceId; + + private String orderAmount; + private Integer orderStatus; + + private Date payTime; + + private transient String createdTime; + private transient String fileMd5; + private transient String mobile; + + private String codeId; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + private String tenantId; + private String company; + private Integer isDel; + + private transient String waylineLinkUrl; + private transient JSONObject streamUrls; + + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/OrderFile.java b/zlt-business/order-center/src/main/java/com/central/order/model/OrderFile.java new file mode 100644 index 00000000..9df9b83f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/OrderFile.java @@ -0,0 +1,49 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * order files information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("order_files") +public class OrderFile extends SuperEntity { + private static final long serialVersionUID=1L; + + private String orderNo; + private String fileId; + + private Long userId; + + private transient String viewUrl; + + //文件缩略图 + private transient String zipViewUrl; + // 景区ID + private Long tourismId; + + private String fileType; + //该Path不包含bucketName + private String filePath; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + //租户ID + private String tenantId; + private Integer isDel; + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/OrderRanking.java b/zlt-business/order-center/src/main/java/com/central/order/model/OrderRanking.java new file mode 100644 index 00000000..087ccd6f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/OrderRanking.java @@ -0,0 +1,13 @@ +package com.central.order.model; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class OrderRanking { + + private Integer ranking; + private Long id; + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/OrderStatistics.java b/zlt-business/order-center/src/main/java/com/central/order/model/OrderStatistics.java new file mode 100644 index 00000000..bcc9bfc0 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/OrderStatistics.java @@ -0,0 +1,44 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.Date; + +@Data +@TableName("order_statistics") +public class OrderStatistics { + private Long id; + + // 统计维度 + private String qrcodeId; // 二维码ID + private Long tourismId; // 景区ID + private String tourismName; // 景区名称 + private String deviceSn; // 设备编号 + private String tenantId; // 租户ID + + // 订单统计 + private Integer totalOrders; // 总订单数 + private Integer paidOrders; // 已支付订单数 + private Integer completedOrders;// 已完成订单数 + private Integer canceledOrders; // 已取消订单数 + + // 金额统计(单位:分) + private Long totalAmount; // 总金额 + private Long paidAmount; // 已支付金额 + private Long refundAmount; // 退款金额 + + // 分账金额 + private BigDecimal platformRate = BigDecimal.ZERO; + private BigDecimal tourismRate = BigDecimal.ZERO; + private Long platformAmount = 0L; + private Long tourismAmount = 0L; + + // 时间维度 + private Date startTime; // 统计开始时间 + private Date endTime; // 统计结束时间 + private String statisticsDate; // 统计日期(yyyy-MM-dd) + private Integer statisticsHour; // 统计小时(0-23) + private Date createTime; // 创建时间 +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java b/zlt-business/order-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java new file mode 100644 index 00000000..d2efde49 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java @@ -0,0 +1,28 @@ +package com.central.order.model; + +import com.central.order.constants.OrderStatusConstants; +import com.central.order.enums.OrderStatus; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class OrderStatisticsQuery { + private String startTime; + private String endTime; + private String qrcodeId; + private Long tourismId; + private String deviceSn; + private String groupField; // 分组字段 + + @Builder.Default + private Integer completeStatus = OrderStatus.COMPLETE.getId(); + @Builder.Default + private Integer cancelStatus = OrderStatus.CANCELED.getId(); + + // 添加状态集合字符串 + @Builder.Default + private String paidStatus = OrderStatusConstants.PAID_STATUS; + @Builder.Default + private String refundStatus = OrderStatusConstants.REFUND_STATUS; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/PaymentRecord.java b/zlt-business/order-center/src/main/java/com/central/order/model/PaymentRecord.java new file mode 100644 index 00000000..41933f83 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/PaymentRecord.java @@ -0,0 +1,43 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * PaymentRecord information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("payment_records") +public class PaymentRecord { + private static final long serialVersionUID = 1L; + + @TableId + private Long id; + private Long orderId; + private String orderNo; + private String paymentNumber; + private Double paymentAmount; + private Date paymentTime; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + private Long createId; + private String company; + private Integer isDel; + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/ProfitSharing.java b/zlt-business/order-center/src/main/java/com/central/order/model/ProfitSharing.java new file mode 100644 index 00000000..2ac3eedb --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/ProfitSharing.java @@ -0,0 +1,165 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.order.enums.PayeeTypeEnum; +import com.central.order.enums.ProfitSharingStatusEnum; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import java.util.Date; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("profit_sharing") +@Schema(description = "分账记录") +public class ProfitSharing { + @TableId + @Schema(description = "主键ID") + private Long id; + + @NotNull(message = "订单ID不能为空") + @Length(max = 64, message = "订单ID长度不能超过64") + @Schema(description = "订单ID") + private String orderId; + + @NotNull(message = "订单编号不能为空") + @Length(max = 64, message = "订单编号长度不能超过64") + @Schema(description = "订单编号") + private String orderNo; + + @Length(max = 64, message = "微信支付订单号长度不能超过64") + @Schema(description = "微信支付订单号") + private String transactionId; + + @Length(max = 64, message = "微信分账单号长度不能超过64") + @Schema(description = "微信分账单号") + @TableField("profit_sharing_id") + private String profitSharingId; + + @NotNull(message = "订单总金额不能为空") + @Min(value = 1, message = "订单总金额必须大于0") + @Schema(description = "订单总金额(分)") + private Long totalAmount; + + @NotNull(message = "平台分账金额不能为空") + @Min(value = 0, message = "平台分账金额不能小于0") + @Schema(description = "平台分账金额(分)") + private Long platformAmount; + + @NotNull(message = "二维码分账金额不能为空") + @Min(value = 1, message = "二维码分账金额必须大于0") + @Schema(description = "二维码分账金额(分)") + @TableField("qrcode_amount") + private Long qrCodeAmount; + + @Schema(description = "分账状态:0-待分账 1-分账中 2-分账成功 3-分账失败") + private Integer status; + + @NotNull(message = "二维码ID不能为空") + @Schema(description = "二维码ID") + private String codeId; + + @NotNull(message = "分账接收账号不能为空") + @Schema(description = "分账接收账号") + @TableField("payee_account") + private String payeeAccount; + + @NotNull(message = "分账账号类型不能为空") + @Schema(description = "分账账号类型:MERCHANT_ID-商户ID,PERSONAL_OPENID-个人openid") + @TableField("payee_type") + private String payeeType; + + @Length(max = 256, message = "分账描述长度不能超过256") + @Schema(description = "分账描述") + @TableField("description") + private String description; + + @Length(max = 256, message = "分账失败原因长度不能超过256") + @Schema(description = "分账失败原因") + @TableField("fail_reason") + private String failReason; + + @Schema(description = "实际分账金额(分)") + @TableField("receiver_amount") + private Long receiverAmount; + + @Schema(description = "分账完成时间") + @TableField("finish_time") + private Date finishTime; + + @Length(max = 64, message = "分账请求号长度不能超过64") + @Schema(description = "分账请求号") + @TableField("out_order_no") + private String outOrderNo; + + @Schema(description = "重试次数") + @TableField("retry_times") + private Integer retryTimes; + + @Schema(description = "最后重试时间") + @TableField("last_retry_time") + private Date lastRetryTime; + + @Schema(description = "创建时间") + private Date createTime; + + @Schema(description = "更新时间") + private Date updateTime; + + private String tenantId; + + /** + * 获取状态描述 + */ + public String getStatusDesc() { + return ProfitSharingStatusEnum.getDesc(status); + } + + /** + * 获取分账账号类型描述 + */ + public String getPayeeTypeDesc() { + return PayeeTypeEnum.getDesc(payeeType); + } + + /** + * 判断是否可以重试 + * 条件: + * 1. 状态为失败 + * 2. 重试次数小于3次 + * 3. 距离上次重试时间超过5分钟 + */ + public boolean canRetry() { + return status == ProfitSharingStatusEnum.FAILED.getCode() + && (retryTimes == null || retryTimes < 3) + && (lastRetryTime == null || System.currentTimeMillis() - lastRetryTime.getTime() > 300000); + } + + /** + * 更新重试信息 + */ + public void updateRetryInfo() { + this.retryTimes = (this.retryTimes == null ? 0 : this.retryTimes) + 1; + this.lastRetryTime = new Date(); + } + + /** + * 检查金额是否合法 + */ + public boolean isAmountValid() { + return totalAmount != null && totalAmount > 0 + && platformAmount != null && platformAmount >= 0 + && qrCodeAmount != null && qrCodeAmount > 0 + && (platformAmount + qrCodeAmount == totalAmount); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/ProfitSharingResult.java b/zlt-business/order-center/src/main/java/com/central/order/model/ProfitSharingResult.java new file mode 100644 index 00000000..d6b8dd0d --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/ProfitSharingResult.java @@ -0,0 +1,104 @@ +package com.central.order.model; + +import com.central.order.enums.ProfitSharingStatusEnum; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Schema(description = "分账结果") +public class ProfitSharingResult { + + @Schema(description = "订单号") + private String orderNo; + + @Schema(description = "微信支付订单号") + private String transactionId; + + @Schema(description = "分账单号") + private String profitSharingId; + + @Schema(description = "分账状态") + private Integer status; + + @Schema(description = "分账状态描述") + private String statusDesc; + + @Schema(description = "分账总金额(分)") + private Long totalAmount; + + @Schema(description = "实际分账金额(分)") + private Long receiverAmount; + + @Schema(description = "分账完成时间") + private Date finishTime; + + @Schema(description = "失败原因") + private String failReason; + + @Schema(description = "分账接收方列表") + private List receivers; + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class ReceiverResult { + @Schema(description = "接收方类型") + private String type; + + @Schema(description = "接收方账号") + private String account; + + @Schema(description = "分账金额(分)") + private Long amount; + + @Schema(description = "分账描述") + private String description; + + @Schema(description = "分账结果") + private String result; + + @Schema(description = "失败原因") + private String failReason; + + @Schema(description = "分账明细单号") + private String detailId; + } + + /** + * 获取状态描述 + */ + public String getStatusDesc() { + return ProfitSharingStatusEnum.getDesc(status); + } + + /** + * 判断分账是否成功 + */ + public boolean isSuccess() { + return ProfitSharingStatusEnum.SUCCESS.getCode() == status; + } + + /** + * 判断分账是否失败 + */ + public boolean isFailed() { + return ProfitSharingStatusEnum.FAILED.getCode() == status; + } + + /** + * 判断分账是否处理中 + */ + public boolean isProcessing() { + return ProfitSharingStatusEnum.PROCESSING.getCode() == status; + } +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/QrCode.java b/zlt-business/order-center/src/main/java/com/central/order/model/QrCode.java new file mode 100644 index 00000000..1ee42371 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/QrCode.java @@ -0,0 +1,96 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.*; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * qrcodes information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@EqualsAndHashCode(callSuper = false) +@TableName("qrcodes") +public class QrCode extends SuperEntity { + + private static final long serialVersionUID=1L; + + private String codeId; + private Long tourismId; + + // 新增二维码名称字段 + private String name; + + private String templateId; + private String filePath; + + private transient String viewUrl; + + private String fileId; + private Integer status; + + private String waylineId; + private String price; + + private String deviceSn; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + //租户ID + private String tenantId; + private String company; + private Integer isDel; + + /** + * 分账接收账号 + */ + + private String payeeAccount; + + /** + * 分账比例(百分比,例如:30.00 表示 30%) + */ + + private BigDecimal profitRate; + + /** + * 分账账号类型(MERCHANT_ID:商户ID,PERSONAL_OPENID:个人openid) + */ + + private String payeeType; + + /** + * 分账账号状态(0:未验证,1:已验证,2:验证失败) + */ + + private Integer payeeStatus; + + @Schema(description = "分账失败原因") + private String payeeFailReason; + + /** + * 是否开启分润(0:否,1:是) + */ + @Schema(description = "是否开启分润") + private Integer enableProfit; + + /** + * 是否开启一键成片(0:否,1:是) + */ + @Schema(description = "是否开启一键成片") + private Integer enableVideoEdit; + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/QrCodeVO.java b/zlt-business/order-center/src/main/java/com/central/order/model/QrCodeVO.java new file mode 100644 index 00000000..198b81df --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/QrCodeVO.java @@ -0,0 +1,26 @@ +package com.central.order.model; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * qrcodes information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +public class QrCodeVO { + + private static final long serialVersionUID=1L; + + private String codeId; + private Tourism tourism; + private List tourismFiles; + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/Refund.java b/zlt-business/order-center/src/main/java/com/central/order/model/Refund.java new file mode 100644 index 00000000..c7ca9120 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/Refund.java @@ -0,0 +1,51 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Refund information + * + * @author lsl + * @date 2025-2-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("orders_refund") +public class Refund extends SuperEntity { + private static final long serialVersionUID=1L; + + private String orderNo; + private String refundNo; + + private Long userId; + private String orderAmount; + private String refundAmount; + private String refundReason; + private String refundImgs; + private Integer status; + + private Integer state; + private String approveReason; + + private Date refundTime; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + private String tenantId; + private String company; + private Integer isDel; + + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/RequestParamsEntity.java b/zlt-business/order-center/src/main/java/com/central/order/model/RequestParamsEntity.java new file mode 100644 index 00000000..716a1ada --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/RequestParamsEntity.java @@ -0,0 +1,38 @@ +package com.central.order.model; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotNull; + +/** + * 一键成片请求参数实体类 + * @author lsl + * + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class RequestParamsEntity { + + @Schema(description = "应用ID") + @NotBlank(message = "应用ID不能为空") + private String appId; + + @Schema(description = "任务ID") + @NotBlank(message = "任务ID不能为空") + private String taskId; + + @Schema(description = "回调地址") + @NotBlank(message = "回调地址不能为空") + private String callbackUrl; + + @Schema(description = "素材来源") + @NotNull(message = "素材来源不能为空") + private SourceDTO source; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/SourceDTO.java b/zlt-business/order-center/src/main/java/com/central/order/model/SourceDTO.java new file mode 100644 index 00000000..ef033105 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/SourceDTO.java @@ -0,0 +1,35 @@ +package com.central.order.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import lombok.Data; +import lombok.Builder; +import lombok.NoArgsConstructor; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.List; + +/** + * 定义请求参数中的sourceDTO类 + * @author lsl + * + */ + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class SourceDTO { + @Schema(description = "文本列表") + private List textList; + + @Schema(description = "视频列表") + private List videoList; + + @Schema(description = "音频列表") + private List audioList; + + @Schema(description = "图片列表") + private List imageList; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/Tourism.java b/zlt-business/order-center/src/main/java/com/central/order/model/Tourism.java new file mode 100644 index 00000000..d0d78196 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/Tourism.java @@ -0,0 +1,46 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("tourisms") +public class Tourism extends SuperEntity { + + private static final long serialVersionUID=1L; + + private String tourismName; + private String tourismDesc; + private Integer type; + private Integer status; + + private String tourismNo; + private String tourismAddress; + private String tourismPhone; + private String tourismEmail; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + //租户ID + private String tenantId; + private String company; + private Integer isDel; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/TourismFile.java b/zlt-business/order-center/src/main/java/com/central/order/model/TourismFile.java new file mode 100644 index 00000000..3492caa8 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/TourismFile.java @@ -0,0 +1,43 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Tourism File information + * + * @author lsl + * @date 2025-2-17 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("tourisms_files") +public class TourismFile extends SuperEntity { + + private static final long serialVersionUID=1L; + + private Long tourismId; + private String imageUrl; + private int type; + private Integer status; + + private String linkUrl; + private String description; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + //租户ID + private String tenantId; + private String company; + private Integer isDel; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/VideoTemplate.java b/zlt-business/order-center/src/main/java/com/central/order/model/VideoTemplate.java new file mode 100644 index 00000000..acb336ba --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/VideoTemplate.java @@ -0,0 +1,52 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.*; +import com.central.common.model.SuperEntity; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("video_template") +@Schema(description = "视频模板") +public class VideoTemplate extends SuperEntity { + + @TableId(type = IdType.AUTO) + @Schema(description = "主键ID") + private Long id; + + @Schema(description = "模板ID") + private String templateId; + + @Schema(description = "模板名称") + private String templateName; + + @Schema(description = "模板描述") + private String description; + + @Schema(description = "状态:0-禁用 1-启用") + private Integer status; + + @Schema(description = "模板配置JSON") + private String config; + + @Schema(description = "创建时间") + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + @Schema(description = "更新时间") + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + @Schema(description = "租户ID") + private Long tenantId; + + @Schema(description = "所属公司") + private String company; + + @Schema(description = "是否删除:0-否 1-是") + private Integer isDel; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/WxMessageRecord.java b/zlt-business/order-center/src/main/java/com/central/order/model/WxMessageRecord.java new file mode 100644 index 00000000..29c765d0 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/WxMessageRecord.java @@ -0,0 +1,32 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("wx_message_record") +public class WxMessageRecord { + @TableId(type = IdType.AUTO) + private Long id; + private String openId; + private String templateId; + private String msgId; + private String content; + private Integer status; + private String errorMsg; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + //租户ID + private Long tenantId; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/WxTemplateInfo.java b/zlt-business/order-center/src/main/java/com/central/order/model/WxTemplateInfo.java new file mode 100644 index 00000000..bb417033 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/WxTemplateInfo.java @@ -0,0 +1,44 @@ +package com.central.order.model; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class WxTemplateInfo { + /** + * 模板ID + */ + private String priTmplId; + + /** + * 模板标题 + */ + private String title; + + /** + * 模板内容 + */ + private String content; + + /** + * 模板示例 + */ + private String example; + + /** + * 类型 + */ + private Integer type; + + /** + * 创建时间 + */ + private Date createTime; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/WxUserSubscribe.java b/zlt-business/order-center/src/main/java/com/central/order/model/WxUserSubscribe.java new file mode 100644 index 00000000..37838285 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/WxUserSubscribe.java @@ -0,0 +1,20 @@ +package com.central.order.model; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class WxUserSubscribe { + private Long id; + private String openId; + private Boolean subscribed; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/dto/CallbackDTO.java b/zlt-business/order-center/src/main/java/com/central/order/model/dto/CallbackDTO.java new file mode 100644 index 00000000..c1bb33d0 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/dto/CallbackDTO.java @@ -0,0 +1,18 @@ +package com.central.order.model.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CallbackDTO { + private String jobId; + private String status; // SUCCESS, FAILED + private String result; // 处理结果,可能包含视频URL或错误信息 + private String errorCode; + private String errorMessage; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/dto/VideoEditRequest.java b/zlt-business/order-center/src/main/java/com/central/order/model/dto/VideoEditRequest.java new file mode 100644 index 00000000..4b48a6c3 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/dto/VideoEditRequest.java @@ -0,0 +1,36 @@ +package com.central.order.model.dto; + +import lombok.Builder; +import lombok.Data; + +import java.util.List; + +@Data +@Builder +public class VideoEditRequest { + private List sources; + private OutputInfo output; + private String templateId; + private String projectName; + private String pipelineName; + private String callbackUrl; + + @Data + @Builder + public static class MediaInfo { + private String mediaUrl; + private String mediaType; // VIDEO, IMAGE, AUDIO + private Integer duration; // 持续时间(毫秒) + private String text; // 文本内容 + } + + @Data + @Builder + public static class OutputInfo { + private String outputName; + private String outputType; // MP4, MOV等 + private Integer width; + private Integer height; + private String quality; // HD, SD等 + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/dto/VideoEditStatus.java b/zlt-business/order-center/src/main/java/com/central/order/model/dto/VideoEditStatus.java new file mode 100644 index 00000000..b9a6f955 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/dto/VideoEditStatus.java @@ -0,0 +1,32 @@ +package com.central.order.model.dto; + +import lombok.Getter; + +/** + * 视频编辑状态枚举 + */ +@Getter +public enum VideoEditStatus { + QUEUED("Queued", "排队中"), + RUNNING("Running", "处理中"), + SUCCESS("Success", "处理成功"), + FAIL("Fail", "处理失败"), + UNKNOWN("Unknown", "未知状态"); + + private final String code; + private final String desc; + + VideoEditStatus(String code, String desc) { + this.code = code; + this.desc = desc; + } + + public static VideoEditStatus fromCode(String code) { + for (VideoEditStatus status : values()) { + if (status.getCode().equals(code)) { + return status; + } + } + return UNKNOWN; + } +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/params/EditTaskQueryParams.java b/zlt-business/order-center/src/main/java/com/central/order/model/params/EditTaskQueryParams.java new file mode 100644 index 00000000..12cdd010 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/params/EditTaskQueryParams.java @@ -0,0 +1,18 @@ +package com.central.order.model.params; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class EditTaskQueryParams { + private Integer page = 1; + private Integer limit = 10; + private String orderSn; + private String jobId; + private Integer status; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/ChartStatistics.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/ChartStatistics.java new file mode 100644 index 00000000..ea106819 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/ChartStatistics.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; + +@Data +@Schema(description = "图表统计数据") +public class ChartStatistics { + @Schema(description = "订单趋势") + private List orderTrend; + + @Schema(description = "设备分布") + private List deviceDistribution; + + @Schema(description = "收入构成") + private List incomeData; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/DashboardStatisticsVO.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/DashboardStatisticsVO.java new file mode 100644 index 00000000..71196488 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/DashboardStatisticsVO.java @@ -0,0 +1,28 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; + +@Data +@Schema(description = "首页统计数据VO") +public class DashboardStatisticsVO { + @Schema(description = "订单统计") + private OrderStatistics orderStats; + + @Schema(description = "收入统计") + private IncomeStatistics incomeStats; + + @Schema(description = "航线统计") + private WaylineStatistics waylineStats; + + @Schema(description = "设备统计") + private DeviceStatistics deviceStats; + + @Schema(description = "图表统计") + private ChartStatistics chartStats; + + @Schema(description = "景区排行") + private List tourismRanking; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/DeviceStatistics.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/DeviceStatistics.java new file mode 100644 index 00000000..672589e3 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/DeviceStatistics.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "设备统计数据") +public class DeviceStatistics { + @Schema(description = "设备总数") + private Long totalDevices; + + @Schema(description = "在线设备数") + private Long onlineDevices; + + @Schema(description = "设备在线率") + private BigDecimal deviceOnlineRate; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/DistributionDataVO.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/DistributionDataVO.java new file mode 100644 index 00000000..0a287a0c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/DistributionDataVO.java @@ -0,0 +1,16 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "分布数据") +public class DistributionDataVO { + @Schema(description = "类型") + private String type; + + @Schema(description = "数值") + private BigDecimal value; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/IncomeDataVO.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/IncomeDataVO.java new file mode 100644 index 00000000..568842b0 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/IncomeDataVO.java @@ -0,0 +1,16 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "收入数据") +public class IncomeDataVO { + @Schema(description = "类型") + private String type; + + @Schema(description = "数值") + private BigDecimal value; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/IncomeStatistics.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/IncomeStatistics.java new file mode 100644 index 00000000..07dbfb4a --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/IncomeStatistics.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "收入统计数据") +public class IncomeStatistics { + @Schema(description = "总收入(分)") + private Long totalAmount; + + @Schema(description = "今日收入(分)") + private Long todayAmount; + + @Schema(description = "目标完成率") + private BigDecimal targetCompletion; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/OrderStatistics.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/OrderStatistics.java new file mode 100644 index 00000000..a91a0098 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/OrderStatistics.java @@ -0,0 +1,22 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "订单统计数据") +public class OrderStatistics { + @Schema(description = "订单总数") + private Long totalOrders; + + @Schema(description = "今日订单数") + private Long todayOrders; + + @Schema(description = "订单增长率") + private BigDecimal orderGrowth; + + @Schema(description = "订单完成率") + private BigDecimal completionRate; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/ProfitSharingStatisticsVO.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/ProfitSharingStatisticsVO.java new file mode 100644 index 00000000..077c906b --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/ProfitSharingStatisticsVO.java @@ -0,0 +1,56 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.Builder; + +import java.util.List; + +@Data +@Builder +@Schema(description = "分账统计数据") +public class ProfitSharingStatisticsVO { + @Schema(description = "总分账笔数") + private Long totalCount; + + @Schema(description = "成功笔数") + private Long successCount; + + @Schema(description = "失败笔数") + private Long failCount; + + @Schema(description = "总分账金额(分)") + private Long totalAmount; + + @Schema(description = "金额趋势数据") + private List amountTrend; + + @Schema(description = "成功率数据") + private List successRate; + + @Data + @Builder + public static class TrendData { + @Schema(description = "日期") + private String date; + + @Schema(description = "类型(DAY-日,WEEK-周,MONTH-月)") + private String type; + + @Schema(description = "金额(分)") + private Long amount; + } + + @Data + @Builder + public static class RateData { + @Schema(description = "日期") + private String date; + + @Schema(description = "类型(DAY-日,WEEK-周,MONTH-月)") + private String type; + + @Schema(description = "成功率(0-100)") + private Double value; + } +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/TourismRankingVO.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/TourismRankingVO.java new file mode 100644 index 00000000..7e30a636 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/TourismRankingVO.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "景区排行数据") +public class TourismRankingVO { + @Schema(description = "景区ID") + private String id; + + @Schema(description = "景区名称") + private String name; + + @Schema(description = "数值") + private BigDecimal value; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/TrendDataVO.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/TrendDataVO.java new file mode 100644 index 00000000..a903059c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/TrendDataVO.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "趋势数据") +public class TrendDataVO { + @Schema(description = "日期") + private String date; + + @Schema(description = "类型") + private String type; + + @Schema(description = "数值") + private BigDecimal value; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/model/vo/WaylineStatistics.java b/zlt-business/order-center/src/main/java/com/central/order/model/vo/WaylineStatistics.java new file mode 100644 index 00000000..54f89bbe --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/model/vo/WaylineStatistics.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "航线统计数据") +public class WaylineStatistics { + @Schema(description = "航线总数") + private Long totalWaylines; + + @Schema(description = "活跃航线数") + private Long activeWaylines; + + @Schema(description = "航线使用率") + private BigDecimal waylineUsage; +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/scheduler/OrderScheduler.java b/zlt-business/order-center/src/main/java/com/central/order/scheduler/OrderScheduler.java new file mode 100644 index 00000000..2ee589e3 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/scheduler/OrderScheduler.java @@ -0,0 +1,31 @@ +package com.central.order.scheduler; + +import com.central.order.service.IOrderService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +@Configuration +@EnableScheduling +public class OrderScheduler { + + @Autowired + private IOrderService orderService; + + // 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况 + @Scheduled(fixedRate = 60 * 1000) + public void checkOrderTimeout() { + orderService.checkAndHandleOrderTimeout(); + } + + // 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查是否存在未服务完成的订单 +// @Scheduled(fixedRate = 60 * 1000) + public void processOrdersInQueue() { + orderService.processOrdersInQueue(); + } + @Scheduled(fixedRate = 2 * 60 * 1000) + public void processOrdersCompleted() {} +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/scheduler/VideoEditTaskChecker.java b/zlt-business/order-center/src/main/java/com/central/order/scheduler/VideoEditTaskChecker.java new file mode 100644 index 00000000..bb320b10 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/scheduler/VideoEditTaskChecker.java @@ -0,0 +1,55 @@ +package com.central.order.scheduler; + +import com.central.order.constants.EditTaskStatus; +import com.central.order.model.EditTask; +import com.central.order.service.IEditTaskService; +import com.central.order.service.IVideoEditService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Slf4j +@Component +public class VideoEditTaskChecker { + + @Autowired + private IEditTaskService editTaskService; + @Autowired + private IVideoEditService videoEditService; + + // 每30秒检查一次任务状态 + @Scheduled(fixedRate = 30000) + public void checkEditTasks() { + try { + // 获取所有处理中的任务 + List processingTasks = editTaskService.getProcessingTasks(); + + for (EditTask task : processingTasks) { + try { + // 检查任务是否超时 + if (isTaskTimeout(task)) { + editTaskService.updateTaskStatus(task.getJobId(), + EditTaskStatus.FAILED, "任务超时"); + continue; + } + + videoEditService.handleEditStatus(task.getJobId()); + + } catch (Exception e) { + log.error("检查任务状态失败: taskId={}", task.getJobId(), e); + } + } + } catch (Exception e) { + log.error("执行任务状态检查失败", e); + } + } + + private boolean isTaskTimeout(EditTask task) { + // 假设2小时超时 + return System.currentTimeMillis() - task.getCreateTime().getTime() > 7200000; + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/scheduler/WxAccessTokenRefreshTask.java b/zlt-business/order-center/src/main/java/com/central/order/scheduler/WxAccessTokenRefreshTask.java new file mode 100644 index 00000000..f21f4945 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/scheduler/WxAccessTokenRefreshTask.java @@ -0,0 +1,29 @@ +package com.central.order.scheduler; + +import com.central.order.service.IWxAccessTokenService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class WxAccessTokenRefreshTask { + + @Autowired + private IWxAccessTokenService wxAccessTokenService; + + /** + * 每100分钟刷新一次access_token + */ +// @Scheduled(initialDelay = 60000, fixedRate = 6000000) + public void refreshAccessToken() { + try { + log.info("开始执行定时刷新access_token任务"); + wxAccessTokenService.refreshAccessToken(); + } catch (Exception e) { + log.error("定时刷新access_token失败", e); + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IDashboardService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IDashboardService.java new file mode 100644 index 00000000..e67974aa --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IDashboardService.java @@ -0,0 +1,10 @@ +package com.central.order.service; + +import com.central.order.model.vo.DashboardStatisticsVO; + +public interface IDashboardService { + /** + * 获取首页统计数据 + */ + DashboardStatisticsVO getDashboardStatistics(); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IEditTaskService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IEditTaskService.java new file mode 100644 index 00000000..6cb96b3f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IEditTaskService.java @@ -0,0 +1,76 @@ +package com.central.order.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.central.common.model.PageResult; +import com.central.order.model.EditTask; +import com.central.order.model.params.EditTaskQueryParams; + +import java.util.List; + +/** + * 视频编辑任务服务接口 + */ +public interface IEditTaskService extends IService { + /** + * 创建编辑任务 + * + * @param orderSn 订单编号 + * @param userId 用户ID + * @return 任务实体 + */ + EditTask createTask(String orderSn, Long userId); + + /** + * 更新任务状态 + * + * @param jobId 任务ID + * @param status 状态 + * @param result 结果信息 + * @return 是否更新成功 + */ + boolean updateTaskStatus(String jobId, Integer status, String result); + + /** + * 根据任务ID获取任务 + * + * @param jobId 任务ID + * @return 任务实体 + */ + EditTask getTaskByJobId(String jobId); + + /** + * 根据订单号获取最新任务 + * + * @param orderSn 订单编号 + * @return 任务实体 + */ + EditTask getTaskByOrderSn(String orderSn); + + /** + * 分页查询剪辑任务 + */ + PageResult getTaskList(EditTaskQueryParams params); + + /** + * 保存或更新剪辑任务 + */ + boolean saveOrUpdateTask(EditTask task); + + /** + * 删除剪辑任务 + */ + boolean deleteTask(Integer id); + + /** + * 获取处理中的任务列表 + * @return 处理中的任务列表 + */ + List getProcessingTasks(); + + /** + * 根据jobId获取编辑任务 + * @param jobId 任务ID + * @return 编辑任务信息 + */ + EditTask getByJobId(String jobId); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IHomeCarouselService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IHomeCarouselService.java new file mode 100644 index 00000000..d19bc980 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IHomeCarouselService.java @@ -0,0 +1,32 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.ISuperService; +import com.central.order.model.HomeCarousel; + +import java.util.Map; + +/** + * HomeCarousel file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IHomeCarouselService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建 + * + * @param tourism + * @return + */ + Result saveOrUpdateHomeCarousel(HomeCarousel tourism) ; +} + diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IMediaService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IMediaService.java new file mode 100644 index 00000000..394dccbb --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IMediaService.java @@ -0,0 +1,25 @@ +package com.central.order.service; + +import com.central.order.model.OrderFile; +import com.central.order.model.TourismFile; +import java.util.List; + +public interface IMediaService { + /** + * 提交编辑任务 + * @param orderNo 订单号 + * @param orderFiles 订单文件列表 + * @return 任务ID + */ + String submitEditTask(String orderNo, List orderFiles); + + /** + * 查询任务状态 + */ + String getTaskStatus(String jobId); + + /** + * 获取任务结果 + */ + String getTaskResult(String jobId); +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IMessageService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IMessageService.java new file mode 100644 index 00000000..58dcb0f1 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IMessageService.java @@ -0,0 +1,36 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.ISuperService; +import com.central.order.model.Message; + +import java.util.Map; + +public interface IMessageService extends ISuperService { + + /** + * 获取消息列表 + */ + PageResult findMessages(Map params); + + /** + * 标记消息已读 + */ + Result markAsRead(Long id); + + /** + * 标记所有消息已读 + */ + Result markAllAsRead(); + + /** + * 删除消息 + */ + Result deleteMessage(Long id); + + /** + * 创建消息 + */ + void createMessage(Message message); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IOrderFileService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderFileService.java new file mode 100644 index 00000000..2dedf00d --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderFileService.java @@ -0,0 +1,88 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.OrderFile; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IOrderFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 列表 + * @param params + * @return + */ + PageResult findListByUser(Map params); + + /** + * 创建订单文件资源 + * + * @param orderFile + * @return + */ + boolean createOrderFile(OrderFile orderFile) ; + + + /** + * 订单编号查询订单文件资源 + * @param orderNo + * @return + */ + List getOrderFileByOrderNo(String orderNo); + + /** + * 订单编号查询订单文件资源 + * @param orderNo + * @return + */ + List getOrderFileByOrderNoAndFileType(String orderNo,String contentType); + + /** + * 用户ID查询订单文件资源 + * @param userId + * @return + */ + List getOrderFileByUserId(Long userId); + + /** + * 文件ID查询订单文件资源 + * @param fileId + * @return + */ + OrderFile getOrderFileByFileId(String fileId); + + /** + * 删除文件 + * + * @param id + * @return + */ + int delete(Long id); + + /** + * 获取订单的视频文件列表 + * @param orderNo 订单号 + * @return 视频文件列表 + */ + List getOrderVideoFiles(String orderNo); + + /** + * 获取订单图片文件 + */ + List getOrderImageFiles(String orderNo); +} + diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java new file mode 100644 index 00000000..08c8685c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderService.java @@ -0,0 +1,92 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.Order; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IOrderService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建订单 + * + * @param order + * @return + */ + boolean createOrder(Order order) ; + + /** + * 超时订单自动检查 + */ + void checkAndHandleOrderTimeout() ; + + /** + * 排队订单 + * @return + */ + List getOrdersInQueue(); + + /** + * 排队订单 + * @return + */ + List getOrdersInQueueByDevice(String deviceSn); + /** + * 排队逻辑处理 + */ + void processOrdersInQueue(); + + /** + * 订单编号查询订单 + * @param orderNumber + * @return + */ + Order getOrderByNumber(String orderNumber); + + /** + * 订单信息更新 + * @param order + * @return + */ + boolean updateOrder(Order order); + + List getOrderCountByStatusAndUser(Long userId, Integer... status); + + Long getOrderCountByStatus(Integer status,Long tourismId); + + Order getOrderByStatusAndUser(Integer status, Long userId, Long tourismId); + + /** + * 获取user订单记录 + * @param params + * @return + */ + PageResult findListByUser(Map params); + + + Integer getOrderRankingByOrderId(Long orderId,Long tourismId); + + /** + * 自动更新订单完成状态 + */ + void autoUpdateOrderStatusToComplete(); + + Long getUnCompleteOrderCount(String deviceSn); + + Order getNextQueueOrder(Long tourismId, Long currentOrderId); +} + diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IOrderStatisticsService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderStatisticsService.java new file mode 100644 index 00000000..16327d2b --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IOrderStatisticsService.java @@ -0,0 +1,64 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.OrderStatistics; + +import java.util.List; +import java.util.Map; + +public interface IOrderStatisticsService extends ISuperService { + // 基础统计 + PageResult findList(Map params); + + /** + * 生成统计数据 + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return 是否生成成功 + */ + boolean generateStatistics(String startTime, String endTime); + + /** + * 按时间维度统计 + * @param qrcodeId 二维码ID + * @param startTime 开始时间 + * @param endTime 结束时间 + * @param timeType 时间类型(hour/day/month) + * @return 统计数据列表,包含: + * - timeGroup: 时间分组 + * - formatTime: 格式化后的时间 + * - totalOrders: 订单总数 + * - totalAmount: 总金额(分) + * - totalAmountYuan: 总金额(元) + */ + List> statisticsByTime(String qrcodeId, String startTime, String endTime, String timeType); + + /** + * 按景区维度统计 + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return 统计数据列表,包含: + * - tourismId: 景区ID + * - tourismName: 景区名称 + * - totalOrders: 订单总数 + * - completedOrders: 已完成订单数 + * - completionRate: 完成率 + * - totalAmountYuan: 总金额(元) + * - paidAmountYuan: 已支付金额(元) + * - refundAmountYuan: 退款金额(元) + */ + List> statisticsByTourism(String startTime, String endTime); + + /** + * 按设备维度统计 + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return 统计数据列表,包含: + * - deviceSn: 设备编号 + * - totalOrders: 订单总数 + * - totalAmountYuan: 总金额(元) + * - usageRate: 设备使用率 + */ + List> statisticsByDevice(String startTime, String endTime); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IPaymentRecordService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IPaymentRecordService.java new file mode 100644 index 00000000..11f1a8b4 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IPaymentRecordService.java @@ -0,0 +1,31 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.PaymentRecord; + +import java.util.Map; + +/** + * PaymentRecord information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IPaymentRecordService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 支付记录 + * @param orderNumber + * @param paymentAmount + * @return + */ + boolean processPayment(String orderNumber, Double paymentAmount); +} + diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IProfitSharingService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IProfitSharingService.java new file mode 100644 index 00000000..62458a18 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IProfitSharingService.java @@ -0,0 +1,60 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.Order; +import com.central.order.model.ProfitSharing; +import com.central.order.model.ProfitSharingResult; +import com.central.order.model.QrCode; +import com.central.order.model.vo.ProfitSharingStatisticsVO; + +import java.util.Map; + +public interface IProfitSharingService extends ISuperService { + /** + * 创建分账记录 + */ + ProfitSharing createProfitSharing(Order order, QrCode qrCode); + + /** + * 更新微信支付订单号 + */ + void updateTransactionId(String orderNo, String transactionId); + + /** + * 执行分账 + */ + void executeProfitSharing(String orderNo); + + /** + * 获取分账记录 + */ + ProfitSharing getByOrderNo(String orderNo); + + /** + * 更新分账状态 + */ + void updateProfitSharingStatus(String orderNo, Integer status); + + /** + * 分页查询分账记录 + */ + PageResult findList(Map params); + + /** + * 重试失败的分账 + */ + void retryFailedProfitSharing(String orderNo); + + /** + * 验证并添加接收者 + */ + boolean validateAndAddReceiver(QrCode qrCode); + + /** + * 查询分账状态 + */ + ProfitSharingResult queryProfitSharingStatus(String orderNo); + + ProfitSharingStatisticsVO getStatistics(); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IQrCodeService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IQrCodeService.java new file mode 100644 index 00000000..fa0ef263 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IQrCodeService.java @@ -0,0 +1,38 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.QrCode; + +import java.util.Map; + +/** + * Qrcode file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IQrCodeService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建 + * + * @param qrCode + * @return + */ + boolean createQrCode(QrCode qrCode) ; + + /** + * id查询 + * @param codeId + * @return + */ + QrCode getByCodeId(String codeId); +} + diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IRefundService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IRefundService.java new file mode 100644 index 00000000..342af85e --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IRefundService.java @@ -0,0 +1,38 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.Refund; + +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IRefundService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建订单 + * + * @param refund + * @return + */ + boolean createRefund(Refund refund) ; + + /** + * + * @param refundNo + */ + Refund getRefundByNo(String refundNo) ; + +} + diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/ITourismFileService.java b/zlt-business/order-center/src/main/java/com/central/order/service/ITourismFileService.java new file mode 100644 index 00000000..8f784653 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/ITourismFileService.java @@ -0,0 +1,40 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.ISuperService; +import com.central.order.model.TourismFile; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface ITourismFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建 + * + * @param tourismFile + * @return + */ + Result saveOrUpdateTourismFile(TourismFile tourismFile) ; + + /** + * id查询 + * @param id + * @return + */ + List getByTourismId(Long id); +} + diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/ITourismService.java b/zlt-business/order-center/src/main/java/com/central/order/service/ITourismService.java new file mode 100644 index 00000000..d63fc9d3 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/ITourismService.java @@ -0,0 +1,39 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.ISuperService; +import com.central.order.model.Tourism; + +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface ITourismService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建 + * + * @param tourism + * @return + */ + Result saveOrUpdateTourism(Tourism tourism) ; + + /** + * id查询 + * @param id + * @return + */ + Tourism getTourismById(Long id); +} + diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IVideoEditService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IVideoEditService.java new file mode 100644 index 00000000..b90dbacc --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IVideoEditService.java @@ -0,0 +1,28 @@ +package com.central.order.service; + +import com.central.order.model.OrderFile; +import com.central.order.model.dto.VideoEditStatus; + +import java.util.List; + +/** + * 视频编辑服务接口 + */ +public interface IVideoEditService { + /** + * 提交编辑任务 + * + * @param orderNo 订单号 + * @param orderFiles 订单相关文件 + * @return 任务ID + */ + String submitEditTask(String orderNo, List orderFiles); + + /** + * 查询编辑任务状态 + * + * @param jobId 任务ID + * @return 任务状态 + */ + VideoEditStatus handleEditStatus(String jobId); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IVideoTemplateService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IVideoTemplateService.java new file mode 100644 index 00000000..b634db3c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IVideoTemplateService.java @@ -0,0 +1,40 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.VideoTemplate; + +import java.util.Map; + +public interface IVideoTemplateService extends ISuperService { + + /** + * 分页查询模板 + */ + PageResult findList(Map params); + + /** + * 添加模板 + */ + boolean saveTemplate(VideoTemplate template); + + /** + * 更新模板 + */ + boolean updateTemplate(VideoTemplate template); + + /** + * 删除模板 + */ + boolean deleteTemplate(Long id); + + /** + * 更新模板状态 + */ + boolean updateStatus(Long id, Integer status); + + /** + * 获取可用模板 + */ + VideoTemplate getActiveTemplate(); +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IWxAccessTokenService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IWxAccessTokenService.java new file mode 100644 index 00000000..2b81ae59 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IWxAccessTokenService.java @@ -0,0 +1,14 @@ +package com.central.order.service; + +public interface IWxAccessTokenService { + /** + * 获取access_token + * @return access_token + */ + String getAccessToken(); + + /** + * 刷新access_token + */ + String refreshAccessToken(); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IWxMessageRecordService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IWxMessageRecordService.java new file mode 100644 index 00000000..3ac730e5 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IWxMessageRecordService.java @@ -0,0 +1,36 @@ +package com.central.order.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.central.common.model.PageResult; +import com.central.order.model.WxMessageRecord; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +public interface IWxMessageRecordService extends IService { + /** + * 分页查询消息记录 + */ + PageResult findRecords(Map params); + + /** + * 保存消息记录 + */ + void saveRecord(String openId, String templateId, String content, String msgId, Integer status); + + /** + * 更新消息状态 + */ + void updateStatus(String msgId, Integer status, String errorMsg); + + /** + * 获取时间范围内的发送统计 + */ + Map getStatistics(LocalDateTime startTime, LocalDateTime endTime); + + /** + * 获取失败的消息记录 + */ + List getFailedRecords(); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IWxTemplateMessageService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IWxTemplateMessageService.java new file mode 100644 index 00000000..c753f597 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IWxTemplateMessageService.java @@ -0,0 +1,9 @@ +package com.central.order.service; + +public interface IWxTemplateMessageService { + /** + * 发送支付成功通知 + */ + void sendPaymentSuccessNotice(String openId, String orderNo, String tourismName, + Integer rank); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/IWxUserService.java b/zlt-business/order-center/src/main/java/com/central/order/service/IWxUserService.java new file mode 100644 index 00000000..65744901 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/IWxUserService.java @@ -0,0 +1,11 @@ +package com.central.order.service; + +public interface IWxUserService { + /** + * 通过 unionId 获取服务号的 openId + * + * @param targetUnionId 目标用户的 unionId + * @return 服务号的 openId,如果未找到则返回 null + */ + String getMpOpenIdByUnionId(String targetUnionId); +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/PaymentService.java b/zlt-business/order-center/src/main/java/com/central/order/service/PaymentService.java new file mode 100644 index 00000000..845909de --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/PaymentService.java @@ -0,0 +1,98 @@ +package com.central.order.service; + +import com.central.common.context.LoginUserContextHolder; +import com.central.common.exception.BusinessException; +import com.central.common.model.SysUser; +import com.central.order.feign.UserCenterService; +import com.central.order.model.Order; +import com.central.order.model.QrCode; +import com.central.wechat.config.WxPayConfigFactory; +import com.central.wechat.entity.WechatConfig; +import com.central.wechat.feign.WechatConfigService; +import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension; +import com.wechat.pay.java.service.payments.jsapi.model.*; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class PaymentService { + @Autowired + private WxPayConfigFactory wxPayConfigFactory; + @Autowired + private UserCenterService userCenterService; + @Autowired + private IOrderService orderService; + @Autowired + private IQrCodeService qrCodeService; + @Autowired + private IProfitSharingService profitSharingService; + @Autowired + private WechatConfigService configService; + + + + public PrepayWithRequestPaymentResponse createPayment(Long orderId) { + // 1. 获取用户和订单信息 + SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId()); + Order order = orderService.getById(orderId); + if (order == null) { + throw new BusinessException("订单数据不存在"); + } + + // 2. 获取二维码信息 + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (qrCode == null) { + throw new BusinessException("二维码不存在"); + } + + // 3. 创建支付请求 + PrepayRequest request = new PrepayRequest(); + + // 设置基本支付信息 + Amount amount = new Amount(); + amount.setTotal(Integer.parseInt(order.getOrderAmount())); + request.setAmount(amount); + + // 从二维码配置中获取支付配置 + WechatConfig payConfig = configService.getConfig("PAY", qrCode.getTenantId()); + request.setAppid(payConfig.getAppId()); + request.setMchid(payConfig.getMerchantId()); + request.setDescription(order.getOrderNo()); + request.setNotifyUrl(payConfig.getNotifyUrl()); + request.setOutTradeNo(order.getOrderNo()); + + // 设置支付者信息 + Payer payer = new Payer(); + payer.setOpenid(user.getOpenId()); + request.setPayer(payer); + + // 设置分账信息 + SettleInfo settleInfo = new SettleInfo(); + if (isEnableProfit(qrCode)) { + settleInfo.setProfitSharing(true); + request.setSettleInfo(settleInfo); + // 创建分账记录 + profitSharingService.createProfitSharing(order, qrCode); + } else { + settleInfo.setProfitSharing(false); + request.setSettleInfo(settleInfo); + } + + // 4. 创建对应租户的支付服务 + JsapiServiceExtension jsapiService = wxPayConfigFactory.createJsapiService(qrCode.getTenantId()); + + // 5. 调用支付接口 + return jsapiService.prepayWithRequestPayment(request); + } + + private boolean isEnableProfit(QrCode qrCode) { + return qrCode != null && + Integer.valueOf(1).equals(qrCode.getEnableProfit()) && + qrCode.getPayeeStatus() != null && + qrCode.getPayeeStatus() == 1 && + qrCode.getPayeeAccount() != null && + qrCode.getProfitRate() != null; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/WxMiniSubscribeService.java b/zlt-business/order-center/src/main/java/com/central/order/service/WxMiniSubscribeService.java new file mode 100644 index 00000000..7ca438da --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/WxMiniSubscribeService.java @@ -0,0 +1,35 @@ +package com.central.order.service; + +public interface WxMiniSubscribeService { + /** + * 支付成功后发送小程序订阅消息 + * @param openId 用户openid + * @param orderName 订单名称 + * @param orderNo 订单编号 + * @param tip 温馨提示 + * @param amount 已付金额 + * @param orderTime 下单时间 + */ + void sendPaySuccessMsg(String openId, String orderName, String orderNo, String tip, String amount, String orderTime); + + /** + * 活动即将开始提醒 + */ + void sendActivityStartMsg(String openId, String place, String activityName, String remark, String activityNo); + + /** + * 一键成片制作完成通知 + */ + void sendVideoEditCompleteMsg(String openId, String taskName, String orderNo, String result); + + /** + * 服务进度提醒订阅消息 + * @param openId + * @param taskName + * @param processDesc + * @param orderNo + * @param orderTime + * @param result + */ + void sendServiceProcessMsg(String openId, String taskName,String processDesc, String orderNo,String orderTime, String result, String pageUrl); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/DashboardServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/DashboardServiceImpl.java new file mode 100644 index 00000000..b54102ea --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/DashboardServiceImpl.java @@ -0,0 +1,123 @@ +package com.central.order.service.impl; + +import com.central.order.mapper.DashboardMapper; +import com.central.order.model.vo.*; +import com.central.order.service.IDashboardService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; + +@Slf4j +@Service +@RequiredArgsConstructor +public class DashboardServiceImpl implements IDashboardService { + + private final DashboardMapper dashboardMapper; + + @Override + public DashboardStatisticsVO getDashboardStatistics() { + DashboardStatisticsVO statistics = new DashboardStatisticsVO(); + + try { + // 1. 获取订单统计 + statistics.setOrderStats(getOrderStatistics()); + + // 2. 获取收入统计 + statistics.setIncomeStats(getIncomeStatistics()); + + // 5. 获取图表统计 + statistics.setChartStats(getChartStatistics()); + + // 6. 获取景区排行 + statistics.setTourismRanking(getTourismRanking()); + + } catch (Exception e) { + log.error("获取仪表盘统计数据失败", e); + } + + return statistics; + } + + /** + * 获取订单统计 + */ + private OrderStatistics getOrderStatistics() { + OrderStatistics stats = new OrderStatistics(); + + // 获取订单总数 + stats.setTotalOrders(dashboardMapper.getTotalOrders()); + + // 获取今日订单数 + stats.setTodayOrders(dashboardMapper.getTodayOrders()); + + // 计算订单增长率 + Long yesterdayOrders = dashboardMapper.getYesterdayOrders(); + if (yesterdayOrders > 0) { + BigDecimal growth = new BigDecimal(stats.getTodayOrders() - yesterdayOrders) + .divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal(100)); + stats.setOrderGrowth(growth); + } + + // 计算完成率 + Long completedOrders = dashboardMapper.getCompletedOrders(); + if (stats.getTotalOrders() > 0) { + BigDecimal completionRate = new BigDecimal(completedOrders) + .divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal(100)); + stats.setCompletionRate(completionRate); + } + + return stats; + } + + /** + * 获取收入统计 + */ + private IncomeStatistics getIncomeStatistics() { + IncomeStatistics stats = new IncomeStatistics(); + + // 获取总收入 + stats.setTotalAmount(dashboardMapper.getTotalIncome()); + + // 获取今日收入 + stats.setTodayAmount(dashboardMapper.getTodayIncome()); + + // 计算目标完成率(假设每日目标10000元) + BigDecimal targetAmount = new BigDecimal(1000000); // 100元 * 100(分) + if (stats.getTodayAmount() > 0) { + BigDecimal completion = new BigDecimal(stats.getTodayAmount()) + .divide(targetAmount, 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal(100)); + stats.setTargetCompletion(completion); + } + + return stats; + } + + /** + * 获取图表统计 + */ + private ChartStatistics getChartStatistics() { + ChartStatistics stats = new ChartStatistics(); + + // 获取订单趋势(最近7天) + stats.setOrderTrend(dashboardMapper.getOrderTrend()); + + // 获取收入构成 + stats.setIncomeData(dashboardMapper.getIncomeData()); + + return stats; + } + + /** + * 获取景区排行 + */ + private List getTourismRanking() { + return dashboardMapper.getTourismRanking(); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/EditTaskServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/EditTaskServiceImpl.java new file mode 100644 index 00000000..a69f2089 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/EditTaskServiceImpl.java @@ -0,0 +1,214 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.central.common.exception.BusinessException; +import com.central.common.model.PageResult; +import com.central.order.constants.EditTaskStatus; +import com.central.order.mapper.EditTaskMapper; +import com.central.order.model.EditTask; +import com.central.order.model.params.EditTaskQueryParams; +import com.central.order.service.IEditTaskService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.Date; +import java.util.List; + +/** + * 视频编辑任务服务实现类 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class EditTaskServiceImpl extends ServiceImpl implements IEditTaskService { + + private final EditTaskMapper editTaskMapper; + + @Override + @Transactional(rollbackFor = Exception.class) + public EditTask createTask(String orderSn, Long userId) { + try { + EditTask task = EditTask.builder() + .orderSn(orderSn) + .userId(userId) + .status(0) // 初始状态:待处理 + .createTime(new Date()) + .build(); + + // 保存任务 + if (!save(task)) { + throw new BusinessException("创建任务失败"); + } + + return task; + } catch (Exception e) { + log.error("创建编辑任务失败: orderSn={}, userId={}", orderSn, userId, e); + throw new BusinessException("创建任务失败: " + e.getMessage()); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateTaskStatus(String jobId, Integer status, String result) { + try { + return update(new LambdaUpdateWrapper() + .eq(EditTask::getJobId, jobId) + .set(EditTask::getStatus, status) + .set(EditTask::getResult, result) + .set(EditTask::getRemark, "状态更新时间:" + new Date())); + } catch (Exception e) { + log.error("更新任务状态失败: jobId={}, status={}", jobId, status, e); + throw new BusinessException("更新任务状态失败: " + e.getMessage()); + } + } + + @Override + public EditTask getTaskByJobId(String jobId) { + try { + return getOne(new LambdaQueryWrapper() + .eq(EditTask::getJobId, jobId)); + } catch (Exception e) { + log.error("查询任务失败: jobId={}", jobId, e); + throw new BusinessException("查询任务失败: " + e.getMessage()); + } + } + + @Override + public EditTask getTaskByOrderSn(String orderSn) { + try { + return getOne(new LambdaQueryWrapper() + .eq(EditTask::getOrderSn, orderSn) + .orderByDesc(EditTask::getId) + .last("LIMIT 1")); + } catch (Exception e) { + log.error("查询订单任务失败: orderSn={}", orderSn, e); + throw new BusinessException("查询订单任务失败: " + e.getMessage()); + } + } + + @Override + public PageResult getTaskList(EditTaskQueryParams params) { + try { + // 构建查询条件 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(StringUtils.hasText(params.getOrderSn()), EditTask::getOrderSn, params.getOrderSn()) + .eq(StringUtils.hasText(params.getJobId()), EditTask::getJobId, params.getJobId()) + .eq(params.getStatus() != null, EditTask::getStatus, params.getStatus()) + .orderByDesc(EditTask::getId); + + // 执行分页查询 + Page page = new Page<>(params.getPage(), params.getLimit()); + Page resultPage = page(page, wrapper); + + // 转换为PageResult + return PageResult.builder() + .data(resultPage.getRecords()) + .resp_code(0) + .count(resultPage.getTotal()) + .build(); + + } catch (Exception e) { + log.error("查询剪辑任务列表失败", e); + throw new BusinessException("查询任务列表失败: " + e.getMessage()); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean saveOrUpdateTask(EditTask task) { + try { + // 参数验证 + validateTask(task); + + // 如果是新增任务 + if (task.getId() == null) { + task.setCreateTime(new Date()); + task.setStatus(EditTaskStatus.PENDING); + } + + // 更新任务 + task.setUpdateTime(new Date()); + return saveOrUpdate(task); + + } catch (Exception e) { + log.error("保存剪辑任务失败: task={}", task, e); + throw new BusinessException("保存任务失败: " + e.getMessage()); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean deleteTask(Integer id) { + try { + // 查询任务 + EditTask task = getById(id); + if (task == null) { + throw new BusinessException("任务不存在"); + } + + // 检查任务状态 + if (EditTaskStatus.isProcessing(task.getStatus())) { + throw new BusinessException("任务处理中,不能删除"); + } + + return removeById(id); + + } catch (Exception e) { + log.error("删除剪辑任务失败: id={}", id, e); + throw new BusinessException("删除任务失败: " + e.getMessage()); + } + } + + @Override + public List getProcessingTasks() { + try { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(EditTask::getStatus, EditTaskStatus.PROCESSING) + .orderByAsc(EditTask::getCreateTime); + return editTaskMapper.selectList(wrapper); + } catch (Exception e) { + log.error("获取处理中的任务列表失败", e); + throw new BusinessException("获取处理中的任务列表失败: " + e.getMessage()); + } + } + + @Override + public EditTask getByJobId(String jobId) { + try { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(EditTask::getJobId, jobId) + .last("LIMIT 1"); // 确保只返回一条记录 + + EditTask task = editTaskMapper.selectOne(wrapper); + if (task == null) { + log.warn("未找到编辑任务: jobId={}", jobId); + } + return task; + + } catch (Exception e) { + log.error("查询编辑任务失败: jobId={}", jobId, e); + throw new BusinessException("查询编辑任务失败: " + e.getMessage()); + } + } + + /** + * 验证任务参数 + */ + private void validateTask(EditTask task) { + if (task == null) { + throw new BusinessException("任务参数不能为空"); + } + if (!StringUtils.hasText(task.getOrderSn())) { + throw new BusinessException("订单编号不能为空"); + } + if (task.getUserId() == null) { + throw new BusinessException("用户ID不能为空"); + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/HomeCarouselServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/HomeCarouselServiceImpl.java new file mode 100644 index 00000000..2e01b6eb --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/HomeCarouselServiceImpl.java @@ -0,0 +1,45 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.HomeCarouselMapper; +import com.central.order.model.HomeCarousel; +import com.central.order.service.IHomeCarouselService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class HomeCarouselServiceImpl extends SuperServiceImpl implements IHomeCarouselService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public Result saveOrUpdateHomeCarousel(HomeCarousel homeCarousel) { + boolean result = saveOrUpdate(homeCarousel); + return result ? Result.succeed(homeCarousel, "操作成功") : Result.failed("操作失败"); + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java new file mode 100644 index 00000000..2f73e27f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java @@ -0,0 +1,279 @@ +package com.central.order.service.impl; + +import com.alibaba.fastjson.JSON; +import com.aliyun.sdk.service.ice20201109.AsyncClient; +import com.aliyun.sdk.service.ice20201109.models.GetMediaProducingJobRequest; +import com.aliyun.sdk.service.ice20201109.models.GetMediaProducingJobResponse; +import com.aliyun.sdk.service.ice20201109.models.SubmitMediaProducingJobRequest; +import com.aliyun.sdk.service.ice20201109.models.SubmitMediaProducingJobResponse; +import com.central.common.exception.BusinessException; +import com.central.order.config.AliyunImsConfig; +import com.central.order.feign.FileCenterService; +import com.central.order.model.Order; +import com.central.order.model.OrderFile; +import com.central.order.model.QrCode; +import com.central.order.service.IMediaService; +import com.central.order.service.IOrderFileService; +import com.central.order.service.IOrderService; +import com.central.order.service.IQrCodeService; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +@Slf4j +@Service +@RequiredArgsConstructor +public class MediaServiceImpl implements IMediaService { + + private static final int TASK_SUBMIT_TIMEOUT = 30; + private static final int TASK_QUERY_TIMEOUT = 10; + private static final String OUTPUT_PATH_FORMAT = "output/%s_%s.mp4"; + + @Autowired + private AsyncClient imsClient; + @Autowired + private AliyunImsConfig imsConfig; + @Autowired + private IQrCodeService qrCodeService; + @Autowired + private IOrderService orderService; + @Autowired + private IOrderFileService orderFileService; + @Autowired + private FileCenterService fileCenterService; + + @Override + public String submitEditTask(String orderNo, List orderFiles) { + try { + // 1. 验证并获取必要数据 + TaskSubmitData taskData = validateAndGetTaskData(orderNo, orderFiles); + + // 2. 构建请求参数 + SubmitMediaProducingJobRequest request = buildSubmitRequest(taskData); + + // 3. 提交任务 + return submitTask(request, taskData); + + } catch (BusinessException e) { + log.error("提交编辑任务失败: orderNo={}, error={}", orderNo, e.getMessage()); + throw e; + } catch (Exception e) { + log.error("提交编辑任务异常: orderNo={}", orderNo, e); + throw new BusinessException("提交任务失败: " + e.getMessage()); + } + } + + @Override + public String getTaskStatus(String jobId) { + try { + GetMediaProducingJobRequest request = GetMediaProducingJobRequest.builder() + .jobId(jobId) + .build(); + + CompletableFuture future = imsClient.getMediaProducingJob(request); + GetMediaProducingJobResponse response = future.get(TASK_QUERY_TIMEOUT, TimeUnit.SECONDS); + + return extractTaskStatus(response); + + } catch (Exception e) { + log.error("查询任务状态失败: jobId={}", jobId, e); + throw new BusinessException("查询任务状态失败: " + e.getMessage()); + } + } + + @Override + public String getTaskResult(String jobId) { + try { + GetMediaProducingJobRequest request = GetMediaProducingJobRequest.builder() + .jobId(jobId) + .build(); + + CompletableFuture future = imsClient.getMediaProducingJob(request); + GetMediaProducingJobResponse response = future.get(TASK_QUERY_TIMEOUT, TimeUnit.SECONDS); + log.info("查询剪辑任务RESPONSE: {}", response.toString()); + if (response != null && response.getBody() != null + && response.getBody().getMediaProducingJob() != null) { + // 返回输出URL + return response.getBody().getMediaProducingJob().getMediaURL(); + } + throw new BusinessException("获取任务结果失败: 响应为空"); + } catch (Exception e) { + log.error("获取任务结果失败: jobId={}", jobId, e); + throw new BusinessException("获取任务结果失败: " + e.getMessage()); + } + } + + /** + * 验证并获取任务数据 + */ + private TaskSubmitData validateAndGetTaskData(String orderNo, List orderFiles) { + // 1. 获取订单信息 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null) { + throw new BusinessException("订单不存在"); + } + + // 2. 获取二维码信息 + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (qrCode == null || qrCode.getTemplateId() == null) { + throw new BusinessException("未配置视频模板ID"); + } + + // 3. 获取视频文件 +// List videoFiles = orderFileService.getOrderVideoFiles(orderNo); + if (orderFiles == null || orderFiles.size() < 7) { + throw new BusinessException("订单视频文件数量不足,至少需要2个视频文件"); + } + + return new TaskSubmitData(order, qrCode, orderFiles); + } + + /** + * 构建提交请求 + */ + private SubmitMediaProducingJobRequest buildSubmitRequest(TaskSubmitData taskData) { + String clipsParam = buildClipsParam(taskData); + String outputConfig = buildOutputConfig(taskData.getOrder().getOrderNo()); + String userData = buildUserData(taskData); + + // 打印请求参数 + logRequestParams(taskData, clipsParam, outputConfig, userData); + + return SubmitMediaProducingJobRequest.builder() + .templateId(taskData.getQrCode().getTemplateId()) + .clipsParam(clipsParam) + .outputMediaConfig(outputConfig) + .userData(userData) + .build(); + } + + /** + * 提交任务 + */ + private String submitTask(SubmitMediaProducingJobRequest request, TaskSubmitData taskData) { + try { + CompletableFuture future = imsClient.submitMediaProducingJob(request); + SubmitMediaProducingJobResponse response = future.get(TASK_SUBMIT_TIMEOUT, TimeUnit.SECONDS); + + if (response != null && response.getBody() != null) { + String jobId = response.getBody().getJobId(); + log.info("提交智能一键成片任务成功: orderNo={}, jobId={}, templateId={}", + taskData.getOrder().getOrderNo(), jobId, taskData.getQrCode().getTemplateId()); + return jobId; + } + throw new BusinessException("提交任务失败: 响应为空"); + } catch (TimeoutException e) { + throw new BusinessException("提交任务超时"); + } catch (Exception e) { + throw new BusinessException("提交任务失败: " + e.getMessage()); + } + } + + /** + * 构建剪辑参数 + */ + private String buildClipsParam(TaskSubmitData taskData) { + try { + Map clips = new HashMap<>(); + List videoFiles = taskData.getVideoFiles(); + //@TODO 后期需要通过模板参数进行动态设置clips参数 + clips.put("1", fileCenterService.getViewUrlByPath(videoFiles.get(4).getFilePath())); + clips.put("2", fileCenterService.getViewUrlByPath(videoFiles.get(5).getFilePath())); + clips.put("3", fileCenterService.getViewUrlByPath(videoFiles.get(6).getFilePath())); + clips.put("4", fileCenterService.getViewUrlByPath(videoFiles.get(0).getFilePath())); + clips.put("5", fileCenterService.getViewUrlByPath(videoFiles.get(1).getFilePath())); + clips.put("6", fileCenterService.getViewUrlByPath(videoFiles.get(2).getFilePath())); + clips.put("7", fileCenterService.getViewUrlByPath(videoFiles.get(3).getFilePath())); + + return JSON.toJSONString(clips); + } catch (Exception e) { + throw new BusinessException("构建剪辑参数失败: " + e.getMessage()); + } + } + + /** + * 构建输出配置 + */ + private String buildOutputConfig(String orderNo) { + try { + Map config = new HashMap<>(); + String outputUrl = String.format("https://%s.%s/" + OUTPUT_PATH_FORMAT, + imsConfig.getBucket(), + imsConfig.getOssEndpoint(), + orderNo, + System.currentTimeMillis() + ); + config.put("MediaURL", outputUrl); + return JSON.toJSONString(config); + } catch (Exception e) { + throw new BusinessException("构建输出配置失败: " + e.getMessage()); + } + } + + /** + * 构建用户数据 + */ + private String buildUserData(TaskSubmitData taskData) { + try { + Map userData = new HashMap<>(); + Order order = taskData.getOrder(); + QrCode qrCode = taskData.getQrCode(); + + userData.put("orderNo", order.getOrderNo()); + userData.put("orderId", order.getId()); + userData.put("codeId", order.getCodeId()); + userData.put("templateId", qrCode.getTemplateId()); + userData.put("timestamp", System.currentTimeMillis()); + userData.put("source", "order_center"); + + return JSON.toJSONString(userData); + } catch (Exception e) { + throw new BusinessException("构建用户数据失败: " + e.getMessage()); + } + } + + /** + * 提取任务状态 + */ + private String extractTaskStatus(GetMediaProducingJobResponse response) { + if (response != null && response.getBody() != null + && response.getBody().getMediaProducingJob() != null) { + return response.getBody().getMediaProducingJob().getStatus(); + } + return "UNKNOWN"; + } + + /** + * 记录请求参数 + */ + private void logRequestParams(TaskSubmitData taskData, String clipsParam, + String outputConfig, String userData) { + log.info("提交任务参数: orderNo={}, templateId={}", + taskData.getOrder().getOrderNo(), taskData.getQrCode().getTemplateId()); + log.info("clips参数: {}", clipsParam); + log.info("输出配置: {}", outputConfig); + log.info("用户数据: {}", userData); + } + + + /** + * 任务提交数据封装类 + */ + @Data + @AllArgsConstructor + private static class TaskSubmitData { + private Order order; + private QrCode qrCode; + private List videoFiles; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/MessageServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/MessageServiceImpl.java new file mode 100644 index 00000000..d0036f95 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/MessageServiceImpl.java @@ -0,0 +1,98 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.context.LoginUserContextHolder; +import com.central.common.context.TenantContextHolder; +import com.central.common.model.LoginAppUser; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.MessageMapper; +import com.central.order.model.Message; +import com.central.order.service.IMessageService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +@RequiredArgsConstructor +public class MessageServiceImpl extends SuperServiceImpl implements IMessageService { + + @Override + public PageResult findMessages(Map params) { + LoginAppUser user = LoginUserContextHolder.getUser(); + + Page page = new Page<>(MapUtils.getInteger(params, "page", 1), + MapUtils.getInteger(params, "limit", 10)); + + List list = baseMapper.findList( + page, + user.getId(), + TenantContextHolder.getTenant(), + params // 作为查询条件传入 + ); + + return PageResult.builder() + .data(list) + .resp_code(0) + .count(page.getTotal()) + .build(); + } + + @Override + public Result markAsRead(Long id) { + try { + int count = baseMapper.markAsRead(id, new Date()); + return count > 0 ? Result.succeed("标记成功") : Result.failed("标记失败"); + } catch (Exception e) { + log.error("标记消息已读失败", e); + return Result.failed("标记失败"); + } + } + + @Override + public Result markAllAsRead() { + try { + int count = baseMapper.markAllAsRead(new Date()); + return count > 0 ? Result.succeed("标记成功") : Result.failed("标记失败"); + } catch (Exception e) { + log.error("标记所有消息已读失败", e); + return Result.failed("标记失败"); + } + } + + @Override + public Result deleteMessage(Long id) { + try { + boolean success = removeById(id); + return success ? Result.succeed("删除成功") : Result.failed("删除失败"); + } catch (Exception e) { + log.error("删除消息失败", e); + return Result.failed("删除失败"); + } + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + @Override + public void createMessage(Message message) { + try { + log.info("开始保存站内信"); + message.setStatus(0); + message.setCreateTime(new Date()); + message.setTenantId(TenantContextHolder.getTenant()); + baseMapper.insert(message); + log.info("站内信保存成功: id={}", message.getId()); + } catch (Exception e) { + log.error("站内信保存失败", e); + throw e; + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderFileServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderFileServiceImpl.java new file mode 100644 index 00000000..127ee83f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderFileServiceImpl.java @@ -0,0 +1,106 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.OrderFileMapper; +import com.central.order.model.OrderFile; +import com.central.order.service.IOrderFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class OrderFileServiceImpl extends SuperServiceImpl implements IOrderFileService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public PageResult findListByUser(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findListByUser(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public boolean createOrderFile(OrderFile orderFile) { + int result = baseMapper.insert(orderFile); + if(result > 0){ + return true; + } + return false; + } + + @Override + public List getOrderFileByOrderNo(String orderNo) { + return baseMapper.getOrderFileByOrderNo(orderNo); + } + + @Override + public List getOrderFileByOrderNoAndFileType(String orderNo, String fileType) { + return baseMapper.getOrderFileByOrderNoAndFileType(orderNo, fileType); + } + + + @Override + public List getOrderFileByUserId(Long userId) { + return baseMapper.getOrderFilesByUserId(userId); + } + + @Override + public OrderFile getOrderFileByFileId(String fileId) { + return baseMapper.getFileByFileId(fileId); + } + + @Override + public int delete(Long id) { + OrderFile orderFile = baseMapper.selectById(id); + if (orderFile != null) { + return baseMapper.deleteById(orderFile.getId()); + } + return 0; + } + + @Override + public List getOrderVideoFiles(String orderNo) { + try { + log.debug("查询订单视频文件: orderNo={}", orderNo); + return baseMapper.getOrderVideoFiles(orderNo); + } catch (Exception e) { + log.error("查询订单视频文件失败: orderNo={}", orderNo, e); + return new ArrayList<>(); + } + } + + @Override + public List getOrderImageFiles(String orderNo) { + return baseMapper.selectList( + new QueryWrapper() + .eq("order_no", orderNo) + .eq("file_type", "image/jpeg") // 假设图片类型为 "image" + .orderByAsc("create_time")); + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java new file mode 100644 index 00000000..c601c902 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java @@ -0,0 +1,318 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.lock.DistributedLock; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.enums.OrderStatus; +import com.central.order.event.OrderStatusChangeEvent; +import com.central.order.feign.UserCenterService; +import com.central.order.mapper.OrderFileMapper; +import com.central.order.mapper.OrderMapper; +import com.central.order.mapper.TourismMapper; +import com.central.order.model.Order; +import com.central.order.model.OrderFile; +import com.central.order.model.OrderRanking; +import com.central.order.service.IOrderService; +import com.central.order.util.DateUtils; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.annotation.Primary; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +@Primary +public class OrderServiceImpl extends SuperServiceImpl implements IOrderService { + + private final static String ORDER_LOCK = "order_lock_"; + + @Autowired + private DistributedLock lock; + + private final ExecutorService executorService = Executors.newFixedThreadPool(10); // 线程池,可根据实际并发量调整大小 + + private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + @Autowired + private OrderMapper orderMapper; + + @Autowired + private TourismMapper tourismMapper; + @Autowired + private OrderFileMapper orderFileMapper; + + @Autowired + private ApplicationEventPublisher eventPublisher; + + @Autowired + private UserCenterService userCenterService; + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + for (Order order : list){ + order.setMobile(userCenterService.findUserById(order.getUserId()).getMobile()); + } + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + // 创建订单,初始状态为"待支付" + @Override + public boolean createOrder(Order order) { + order.setOrderStatus(OrderStatus.UNPAID.getId()); + String orderNo = generateOrderNumber(order.getTourismId()); + order.setOrderNo(orderNo); + + // 幂等性校验:同一用户、同一二维码、未完成订单只能有一条 @TODO +// String lockKey = "order:create:" + order.getUserId() + ":" + order.getCodeId(); + try { + return super.saveIdempotency(order, lock + , ORDER_LOCK+orderNo, new QueryWrapper().eq("order_no", orderNo), "订单已存在"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + // 异步检查支付超时任务 + @Async + public void checkPayTimeoutAsync(Long orderId) { + // Thread.sleep(5 * 60 * 1000); // 等待5分钟(模拟支付超时时间) + Order order = baseMapper.getOrderById(orderId); + if (order!= null && OrderStatus.PAID.getId().equals(order.getOrderStatus())) { + baseMapper.updateOrderStatus(orderId, OrderStatus.PAID.getId()); + } + } + + // 检查并处理订单超时逻辑,5分钟超时后自动取消 + @Override + public void checkAndHandleOrderTimeout() { + List orders = baseMapper.getOrdersByStatus(OrderStatus.UNPAID.getId()); + long currentTime = new Date().getTime(); + for (Order order : orders) { + long elapsedTime = currentTime - order.getCreateTime().getTime(); + if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= 5) { + baseMapper.updateOrderStatus(order.getId(), OrderStatus.CANCELED.getId()); + } + } + } + + // 获取所有处于排队状态的订单,用于后续按顺序处理 + @Override + public List getOrdersInQueue() { + return baseMapper.getOrdersInQueue(); + } + + @Override + public List getOrdersInQueueByDevice(String deviceSn) { + + return baseMapper.selectList(new QueryWrapper() + .eq("device_sn", deviceSn) + .eq("order_status", OrderStatus.PAID.getId()) + .orderByAsc("id")); + } + + // 处理排队中的订单,当排在前面的用户消费完成后通知下一位用户进行消费操作(此处简化逻辑,实际需结合业务深入实现) + @Override + public void processOrdersInQueue() { + List queueOrders = getOrdersInQueue(); + for (Order order : queueOrders) { + executorService.submit(() -> { + try { + order.setOrderStatus(OrderStatus.DOING.getId()); + updateOrder(order); // 这里会触发事件发布 + } catch (Exception e) { + log.error("处理队列订单失败", e); + } + }); + } + } + + @Override + public Order getOrderByNumber(String orderNumber) { + return baseMapper.getOrderByNumber(orderNumber); + } + + @Override + public boolean updateOrder(Order order) { + try { + // 获取原订单信息 + Order oldOrder = getById(order.getId()); + boolean result = super.saveOrUpdateIdempotency(order, lock, + ORDER_LOCK + order.getOrderNo(), + new QueryWrapper().eq("order_no", order.getOrderNo()), + "订单已存在"); + + // 如果更新成功且状态发生变化,发布事件 + if (result && !order.getOrderStatus().equals(oldOrder.getOrderStatus())) { + // 发布事件前添加日志 + log.info("准备发布订单状态变更事件: orderNo={}, oldStatus={}, newStatus={}", + order.getOrderNo(), oldOrder.getOrderStatus(), order.getOrderStatus()); + + OrderStatusChangeEvent event = new OrderStatusChangeEvent( + this, + oldOrder.getOrderNo(), + oldOrder.getOrderStatus(), + order.getOrderStatus(), + oldOrder.getUserId(), + String.format("订单金额:%.2f分", + order.getOrderAmount() != null && !order.getOrderAmount().isEmpty() + ? Double.parseDouble(order.getOrderAmount().trim()) + : 0.0) + ); + + eventPublisher.publishEvent(event); + log.info("订单状态变更事件发布成功"); + } + return result; + } catch (Exception e) { + log.error("更新订单失败", e); + throw new RuntimeException(e); + } + } + + @Override + public List getOrderCountByStatusAndUser(Long userId, Integer... status) { + return baseMapper.selectList(new QueryWrapper() + .in("order_status", status) + .eq("user_id", userId)); + + } + + @Override + public Long getOrderCountByStatus(Integer status, Long tourismId) { + return baseMapper.selectCount(new QueryWrapper() + .eq("order_status", status).eq("tourism_id", tourismId)); + } + + @Override + public Order getOrderByStatusAndUser(Integer status, Long userId, Long tourismId) { + return baseMapper.selectOne(new QueryWrapper() + .eq("order_status", status) + .eq("user_id", userId) + .eq("tourism_id", tourismId)); + } + + @Override + public PageResult findListByUser(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findListByUser(page, params); + if (list != null && !list.isEmpty()) { + for (Order order : list) { + order.setTourismName(tourismMapper.getTourismById(order.getTourismId()).getTourismName()); + order.setCreatedTime(sdf.format(order.getCreateTime())); + } + } + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public Integer getOrderRankingByOrderId(Long orderId,Long tourismId) { + + List result = orderMapper.getOrderRanking1(tourismId); + if (!result.isEmpty()) { + for (OrderRanking order : result) { + if (order.getId().equals(orderId)) { + return order.getRanking(); + } + } + } + return 0; + } + + @Override + public void autoUpdateOrderStatusToComplete() { + List orders = baseMapper.getOrdersByStatus(OrderStatus.DOING.getId()); + if (!orders.isEmpty()){ + for (Order order : orders) { + List orderFiles = orderFileMapper.getOrderFileByOrderNo(order.getOrderNo()); + if (!orderFiles.isEmpty()) { + order.setOrderStatus(OrderStatus.COMPLETE.getId()); + orderMapper.updateById(order); + continue; + } + if (DateUtils.isWithinFiveMinutesByNow(order.getUpdateTime())) { + order.setOrderStatus(OrderStatus.COMPLETE.getId()); + orderMapper.updateById(order); + } + } + } + } + + @Override + public Long getUnCompleteOrderCount(String deviceSn) { + return baseMapper.selectCount(new QueryWrapper() + .eq("device_sn", deviceSn) + .in("order_status", OrderStatus.UPLOADING.getId(),OrderStatus.DOING.getId())); + } + + // 生成订单编号 + public String generateOrderNumber(Long tourismId) { + // 获取当前日期,格式化为 yyyyMMdd + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + Date date = new Date(); + String currentDate = sdf.format(date); + + // 获取当天的起始时间和结束时间,用于查询当天订单数量 + Date startDate = DateUtils.getStartOfDay(date); + Date endDate = DateUtils.getEndOfDay(date); + + // 查询当天已有的订单数量 + List existingOrders = baseMapper.findByShopIdAndCreateTimeGreaterThanEqualAndCreateTimeLessThanEqual(tourismId, startDate, endDate); + int orderCount = existingOrders.size(); + + // 生成当天订单序号,从1开始自增 + int orderSequence = orderCount + 1; + + // 格式化订单序号,确保序号长度固定(例如不足3位前面补0) + String formattedSequence = String.format("%05d", orderSequence); + + // 拼接店铺编号、日期、订单序号形成订单编号 + return tourismId + currentDate + formattedSequence; + } + + @Override + public Order getNextQueueOrder(Long tourismId, Long currentOrderId) { + // 1. 查询当前订单 + Order currentOrder = baseMapper.selectById(currentOrderId); + if (currentOrder == null) { + return null; + } + + // 2. 查询下一个排队订单 + // 假设排队顺序按 createTime 升序,且 orderStatus=1(排队中) + // 你可以根据实际业务调整 orderStatus 的值 + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("tourism_id", tourismId) + .eq("order_status", OrderStatus.PAID.getId()) // 1=排队中,具体值请根据你的枚举定义 + .gt("pay_time", currentOrder.getPayTime()) + .orderByAsc("pay_time") + .last("limit 1"); + + return baseMapper.selectOne(wrapper); + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java new file mode 100644 index 00000000..f52e409d --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java @@ -0,0 +1,303 @@ +package com.central.order.service.impl; + +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.OrderStatisticsMapper; +import com.central.order.model.OrderStatistics; +import com.central.order.model.OrderStatisticsQuery; +import com.central.order.service.IOrderStatisticsService; +import com.central.order.service.IQrCodeService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class OrderStatisticsServiceImpl extends SuperServiceImpl implements IOrderStatisticsService { + + @Autowired + private OrderStatisticsMapper orderStatisticsMapper; + + @Autowired + private IQrCodeService qrCodeService; + + @Override + public PageResult findList(Map params) { + return null; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean generateStatistics(String startTime, String endTime) { + try { + // 使用新的查询方法 + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .build(); + + List> statisticsList = orderStatisticsMapper.getOrderStatistics(query); + + for (Map statistics : statisticsList) { + OrderStatistics orderStatistics = new OrderStatistics(); + + // 设置基础信息 + orderStatistics.setQrcodeId(String.valueOf(statistics.get("qrcodeId"))); + orderStatistics.setTourismId(getLongValue(statistics.get("tourismId"))); + orderStatistics.setTourismName(String.valueOf(statistics.get("tourismName"))); + orderStatistics.setDeviceSn(String.valueOf(statistics.get("deviceSn"))); + + // 设置订单统计 + orderStatistics.setTotalOrders(getIntegerValue(statistics.get("totalOrders"))); + orderStatistics.setPaidOrders(getIntegerValue(statistics.get("paidOrders"))); + orderStatistics.setCompletedOrders(getIntegerValue(statistics.get("completedOrders"))); + orderStatistics.setCanceledOrders(getIntegerValue(statistics.get("canceledOrders"))); + + // 设置金额统计 + orderStatistics.setTotalAmount(getLongValue(statistics.get("totalAmount"))); + orderStatistics.setPaidAmount(getLongValue(statistics.get("paidAmount"))); + orderStatistics.setRefundAmount(getLongValue(statistics.get("refundAmount"))); + + // 设置默认分账比例和金额 + BigDecimal platformRate = new BigDecimal("0.30"); + BigDecimal tourismRate = new BigDecimal("0.70"); + + orderStatistics.setPlatformRate(platformRate); + orderStatistics.setTourismRate(tourismRate); + + // 计算分账金额 + Long paidAmount = orderStatistics.getPaidAmount(); + if (paidAmount == null) { + paidAmount = 0L; + } + + // 计算平台分成金额 + Long platformAmount = platformRate + .multiply(new BigDecimal(paidAmount)) + .divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP) + .longValue(); + orderStatistics.setPlatformAmount(platformAmount); + + // 计算景区分成金额 + Long tourismAmount = tourismRate + .multiply(new BigDecimal(paidAmount)) + .divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP) + .longValue(); + orderStatistics.setTourismAmount(tourismAmount); + + // 设置时间 + orderStatistics.setStartTime(parseDateTime(startTime)); + orderStatistics.setEndTime(parseDateTime(endTime)); + orderStatistics.setCreateTime(new Date()); + + // 设置统计日期 + SimpleDateFormat dateSdf = new SimpleDateFormat("yyyy-MM-dd"); + orderStatistics.setStatisticsDate(dateSdf.format(new Date())); + + // 设置统计小时 + Calendar cal = Calendar.getInstance(); + orderStatistics.setStatisticsHour(cal.get(Calendar.HOUR_OF_DAY)); + + // 保存统计数据 + orderStatisticsMapper.insert(orderStatistics); + } + + return true; + } catch (Exception e) { + log.error("生成统计数据失败", e); + throw new RuntimeException("生成统计数据失败", e); + } + } + + // 安全的Integer转换方法 + private Integer getIntegerValue(Object value) { + if (value == null) { + return 0; + } + if (value instanceof Integer) { + return (Integer) value; + } + if (value instanceof Long) { + return ((Long) value).intValue(); + } + try { + return Integer.parseInt(value.toString()); + } catch (NumberFormatException e) { + return 0; + } + } + + // 安全的Long转换方法 + private Long getLongValue(Object value) { + if (value == null) { + return 0L; + } + if (value instanceof Long) { + return (Long) value; + } + if (value instanceof Integer) { + return ((Integer) value).longValue(); + } + try { + return Long.parseLong(value.toString()); + } catch (NumberFormatException e) { + return 0L; + } + } + + // 日期转换方法 + private Date parseDateTime(String dateTimeStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return sdf.parse(dateTimeStr); + } catch (ParseException e) { + log.error("日期解析失败: {}", dateTimeStr, e); + return new Date(); + } + } + + @Override + // 在Service层添加缓存注解 +// @Cacheable(value = "orderStatistics", key = "#startTime + #endTime + #timeType") + public List> statisticsByTime(String qrcodeId, String startTime, String endTime, String timeType) { + try { + String groupField; + switch (timeType) { + case "hour": + groupField = "DATE_FORMAT(o.create_time, '%Y-%m-%d %H:00:00')"; + break; + case "day": + groupField = "DATE_FORMAT(o.create_time, '%Y-%m-%d')"; + break; + case "month": + groupField = "DATE_FORMAT(o.create_time, '%Y-%m')"; + break; + default: + groupField = "DATE_FORMAT(o.create_time, '%Y-%m-%d')"; + } + + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .qrcodeId(qrcodeId) + .groupField(groupField) + .build(); + + List> statistics = baseMapper.getOrderStatisticsByGroup(query); + return processStatisticsResult(statistics); + } catch (Exception e) { + log.error("按时间维度统计失败", e); + return List.of(); + } + } + + @Override + public List> statisticsByTourism(String startTime, String endTime) { + try { + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .groupField("o.tourism_id") + .build(); + + List> statistics = baseMapper.getOrderStatisticsByGroup(query); + return processStatisticsResult(statistics); + } catch (Exception e) { + log.error("按景区维度统计失败", e); + return List.of(); + } + } + + @Override + public List> statisticsByDevice(String startTime, String endTime) { + try { + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .groupField("o.device_sn") + .build(); + + List> statistics = baseMapper.getOrderStatisticsByGroup(query); + return processStatisticsResult(statistics); + } catch (Exception e) { + log.error("按设备维度统计失败", e); + return List.of(); + } + } + + /** + * 处理统计结果 + */ + private List> processStatisticsResult(List> statistics) { + for (Map stat : statistics) { + // 添加金额格式化(转换为元) + Long totalAmount = getLongValue(stat.get("totalAmount")); + Long paidAmount = getLongValue(stat.get("paidAmount")); + Long refundAmount = getLongValue(stat.get("refundAmount")); + + stat.put("totalAmountYuan", formatAmount(totalAmount)); + stat.put("paidAmountYuan", formatAmount(paidAmount)); + stat.put("refundAmountYuan", formatAmount(refundAmount)); + + // 计算完成率 + Integer totalOrders = getIntegerValue(stat.get("totalOrders")); + Integer completedOrders = getIntegerValue(stat.get("completedOrders")); + if (totalOrders > 0) { + double completionRate = (completedOrders * 100.0) / totalOrders; + stat.put("completionRate", String.format("%.2f%%", completionRate)); + } else { + stat.put("completionRate", "0.00%"); + } + } + return statistics; + } + + // 格式化金额 + private String formatAmount(Long amount) { + if (amount == null) { + return "0.00"; + } + return String.format("%.2f", amount / 100.0); + } + + // 格式化时间组 + private String formatTimeGroup(String timeGroup, String timeType) { + if (timeGroup == null) { + return ""; + } + try { + SimpleDateFormat inputFormat; + SimpleDateFormat outputFormat; + switch (timeType) { + case "hour": + inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00"); + outputFormat = new SimpleDateFormat("MM-dd HH:00"); + break; + case "day": + inputFormat = new SimpleDateFormat("yyyy-MM-dd"); + outputFormat = new SimpleDateFormat("MM-dd"); + break; + case "month": + inputFormat = new SimpleDateFormat("yyyy-MM"); + outputFormat = new SimpleDateFormat("yyyy-MM"); + break; + default: + return timeGroup; + } + Date date = inputFormat.parse(timeGroup); + return outputFormat.format(date); + } catch (ParseException e) { + return timeGroup; + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/PaymentRecordServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/PaymentRecordServiceImpl.java new file mode 100644 index 00000000..df891c15 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/PaymentRecordServiceImpl.java @@ -0,0 +1,96 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.lock.DistributedLock; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.enums.OrderStatus; +import com.central.order.mapper.PaymentRecordMapper; +import com.central.order.model.Order; +import com.central.order.model.PaymentRecord; +import com.central.order.service.IOrderService; +import com.central.order.service.IPaymentRecordService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class PaymentRecordServiceImpl extends SuperServiceImpl implements IPaymentRecordService { + + // 定义分布式锁的键,确保唯一性,这里以固定字符串加上当前时间戳来构造 + private final static String PAYMENT_RECORD_LOCK = "payment_records_lock_"; + + private final static String ORDER_LOCK = "order_lock_"; + + @Autowired + private DistributedLock lock; + + @Autowired + private IOrderService orderService; + + /** + * 列表 + * + * @param params + * @return + */ + @Override + public PageResult findList(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + // 处理订单支付逻辑,处理并发冲突和重复支付等问题 + @Transactional + public boolean processPayment(String orderNumber, Double paymentAmount) { + // 生成唯一支付流水号,用于幂等性判断 + String paymentNumber = UUID.randomUUID().toString(); + + // 幂等性判断,查询是否已存在相同支付流水号的支付记录 + PaymentRecord existingRecord = baseMapper.getPaymentRecordByNumber(paymentNumber); + if (existingRecord != null) { + return true; // 已存在记录,说明支付已处理过,直接返回成功 + } + + // 根据订单编号查询订单信息 + Order order = orderService.getOrderByNumber(orderNumber); + if (order == null || !OrderStatus.UNPAID.getId().equals(order.getOrderStatus())) { + return false; // 订单不存在或状态不符合支付条件,返回失败 + } + PaymentRecord paymentRecord = new PaymentRecord(); + paymentRecord.setOrderNo(orderNumber); + paymentRecord.setPaymentAmount(paymentAmount); + paymentRecord.setOrderId(order.getId()); + paymentRecord.setPaymentNumber(paymentNumber); + paymentRecord.setPaymentAmount(paymentAmount); + try { + order.setOrderStatus(OrderStatus.PAID.getId()); + // 执行支付操作,更新订单状态为已支付,插入支付记录(在事务中保证原子性) + boolean res = orderService.saveOrUpdateIdempotency(order, lock + , ORDER_LOCK + orderNumber, new QueryWrapper().eq("order_no", orderNumber), "状态已更新"); + if (res) { + return super.saveIdempotency(paymentRecord, lock + , PAYMENT_RECORD_LOCK + paymentNumber, new QueryWrapper().eq("payment_no", paymentNumber), "订单已存在"); + + } + return false; + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/ProfitSharingServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/ProfitSharingServiceImpl.java new file mode 100644 index 00000000..d51a99af --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/ProfitSharingServiceImpl.java @@ -0,0 +1,762 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.exception.BusinessException; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.config.ProfitSharingProperties; +import com.central.order.constants.ProfitSharingConstants; +import com.central.order.enums.ProfitSharingStatusEnum; +import com.central.order.mapper.ProfitSharingMapper; +import com.central.order.model.Order; +import com.central.order.model.ProfitSharing; +import com.central.order.model.ProfitSharingResult; +import com.central.order.model.QrCode; +import com.central.order.model.vo.ProfitSharingStatisticsVO; +import com.central.order.service.IProfitSharingService; +import com.central.order.service.IQrCodeService; +import com.central.wechat.config.WxPayConfigFactory; +import com.central.wechat.feign.WechatConfigService; +import com.wechat.pay.java.service.profitsharing.model.*; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.time.DateUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Slf4j +@Service +public class ProfitSharingServiceImpl extends SuperServiceImpl implements IProfitSharingService { + + @Autowired + private WechatConfigService wechatConfigService; + + @Autowired + private WxPayConfigFactory wxPayConfigFactory; + + @Autowired + private IQrCodeService qrCodeService; + + @Autowired + private ProfitSharingProperties profitSharingProperties; + + @Autowired + private ProfitSharingMapper profitSharingMapper; + + @Override + @Transactional(rollbackFor = Exception.class) + public ProfitSharing createProfitSharing(Order order, QrCode qrCode) { + try { + // 1. 参数校验 + if (order == null || order.getCodeId() == null) { + throw new IllegalArgumentException("订单或二维码ID不能为空"); + } + + // 3. 验证分账账号 + validatePayeeAccount(qrCode); + + // 4. 计算分账金额 + long totalAmount = Long.parseLong(order.getOrderAmount()); + if (totalAmount <= 0) { + throw new IllegalArgumentException("订单金额必须大于0"); + } + + // 使用二维码的分账比例计算 + long qrCodeAmount = calculateQrCodeAmount(totalAmount, qrCode.getProfitRate()); + long platformAmount = totalAmount - qrCodeAmount; + + // 5. 创建分账记录 + ProfitSharing profitSharing = ProfitSharing.builder() + .orderId(order.getId().toString()) + .orderNo(order.getOrderNo()) + .totalAmount(totalAmount) + .platformAmount(platformAmount) + .qrCodeAmount(qrCodeAmount) + .payeeAccount(qrCode.getPayeeAccount()) + .payeeType(qrCode.getPayeeType()) + .codeId(qrCode.getCodeId()) + .status(0) + .tenantId(qrCode.getTenantId()) + .createTime(new Date()) + .updateTime(new Date()) + .build(); + + // 6. 保存记录 + save(profitSharing); + log.info("创建分账记录成功: {}", profitSharing); + + return profitSharing; + } catch (Exception e) { + log.error("创建分账记录失败: orderId={}, codeId={}", order.getId(), order.getCodeId(), e); + throw new RuntimeException("创建分账记录失败", e); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updateTransactionId(String orderNo, String transactionId) { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing != null) { + profitSharing.setTransactionId(transactionId); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void executeProfitSharing(String orderNo) { + try { + // 1. 获取并验证分账记录 + ProfitSharing profitSharing = validateProfitSharingRecord(orderNo); + + // 2. 检查状态和重试次数 + if (!canExecuteProfitSharing(profitSharing)) { + return; + } + + // 3. 更新状态为处理中 + updateProfitSharingStatus(orderNo, ProfitSharingConstants.Status.PROCESSING); + + // 4. 构建并执行分账请求 + OrdersEntity response = executeProfitSharingRequest(profitSharing); + + // 5. 处理响应 + handleProfitSharingResponse(orderNo, response); + + } catch (Exception e) { + handleProfitSharingError(orderNo, e); + } + } + + private ProfitSharing validateProfitSharingRecord(String orderNo) { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing == null) { + throw new BusinessException("分账记录不存在"); + } + if (StringUtils.isEmpty(profitSharing.getTransactionId())) { + throw new BusinessException("支付交易号不存在"); + } + return profitSharing; + } + + private boolean canExecuteProfitSharing(ProfitSharing profitSharing) { + if (profitSharing.getStatus() == ProfitSharingConstants.Status.SUCCESS) { + log.info("分账已成功完成: {}", profitSharing.getOrderNo()); + return false; + } + + if (profitSharing.getRetryTimes() >= profitSharingProperties.getMaxRetryTimes()) { + log.warn("分账重试次数超限: {}", profitSharing.getOrderNo()); + return false; + } + + return true; + } + + private OrdersEntity executeProfitSharingRequest(ProfitSharing profitSharing) { + CreateOrderRequest request = buildProfitSharingRequest(profitSharing); + try { + return wxPayConfigFactory.createProfitsharingService(profitSharing.getTenantId()).createOrder(request); + } catch (Exception e) { + log.error("调用微信分账接口失败", e); + throw new BusinessException("分账请求失败"); + } + } + + @Async + public void retryFailedProfitSharing(String orderNo) { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing == null || !canRetry(profitSharing)) { + return; + } + + try { + // 更新重试信息 + updateRetryInfo(profitSharing); + + // 执行分账 + executeProfitSharing(orderNo); + + } catch (Exception e) { + log.error("重试分账失败: orderNo={}", orderNo, e); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean validateAndAddReceiver(QrCode qrCode) { + try { + // 1. 参数校验 + if (qrCode == null) { + log.error("二维码信息为空"); + return false; + } + + if (StringUtils.isEmpty(qrCode.getPayeeAccount())) { + log.error("分账接收方账号为空: codeId={}", qrCode.getCodeId()); + return false; + } + + if (StringUtils.isEmpty(qrCode.getPayeeType())) { + log.error("分账接收方类型为空: codeId={}", qrCode.getCodeId()); + return false; + } + + // 2. 构建添加接收方请求 + AddReceiverRequest request = new AddReceiverRequest(); + request.setAppid(wechatConfigService.getConfig("PAY",qrCode.getTenantId()).getAppId()); + + // 设置接收方类型 + try { + request.setType(ReceiverType.valueOf(qrCode.getPayeeType())); + } catch (IllegalArgumentException e) { + log.error("无效的接收方类型: type={}", qrCode.getPayeeType()); + updateReceiverStatus(qrCode, 2, "无效的接收方类型"); + return false; + } + + // 设置接收方账号和名称 + request.setAccount(qrCode.getPayeeAccount()); + request.setName(qrCode.getName()); + request.setRelationType(ReceiverRelationType.CUSTOM); + + // 3. 调用微信接口添加接收方 + try { + AddReceiverResponse response = wxPayConfigFactory.createProfitsharingService(qrCode.getTenantId()).addReceiver(request); + + // 4. 处理响应结果 + if (response != null && response.getAccount() != null) { + // 更新接收方状态为验证成功 + updateReceiverStatus(qrCode, 1, null); + log.info("添加分账接收方成功: account={}", qrCode.getPayeeAccount()); + return true; + } else { + log.error("添加分账接收方失败: response={}", response); + updateReceiverStatus(qrCode, 2, "接口返回为空"); + return false; + } + + } catch (Exception e) { + String errorMsg = getErrorMessage(e); + log.error("添加分账接收方异常: account={}, error={}", qrCode.getPayeeAccount(), errorMsg); + updateReceiverStatus(qrCode, 2, errorMsg); + return false; + } + + } catch (Exception e) { + log.error("验证并添加分账接收方失败", e); + updateReceiverStatus(qrCode, 2, "系统异常"); + return false; + } + } + + /** + * 更新接收方状态 + */ + private void updateReceiverStatus(QrCode qrCode, Integer status, String failReason) { + try { + qrCode.setPayeeStatus(status); + if (failReason != null) { + // 假设QrCode类中有payeeFailReason字段 + qrCode.setPayeeFailReason(failReason); + } + qrCode.setUpdateTime(new Date()); + qrCodeService.updateById(qrCode); + } catch (Exception e) { + log.error("更新接收方状态失败: codeId={}, status={}", qrCode.getCodeId(), status, e); + } + } + + /** + * 验证接收方类型是否合法 + */ + private boolean isValidReceiverType(String type) { + try { + ReceiverType.valueOf(type); + return true; + } catch (IllegalArgumentException e) { + return false; + } + } + + /** + * 获取格式化的错误信息 + */ + private String getErrorMessage(Exception e) { + String message = e.getMessage(); + if (message == null) { + return "未知错误"; + } + // 移除敏感信息 + message = message.replaceAll("\\{\"password\":\"[^\"]*\"\\}", "{\"password\":\"***\"}"); + // 限制长度 + return message.length() > 200 ? message.substring(0, 200) : message; + } + + private boolean canRetry(ProfitSharing profitSharing) { + return profitSharing.getStatus() == ProfitSharingStatusEnum.FAILED.getCode() + && (profitSharing.getRetryTimes() == null + || profitSharing.getRetryTimes() < profitSharingProperties.getMaxRetryTimes()) + && (profitSharing.getLastRetryTime() == null + || System.currentTimeMillis() - profitSharing.getLastRetryTime().getTime() + > profitSharingProperties.getRetryInterval()); + } + + private void updateRetryInfo(ProfitSharing profitSharing) { + profitSharing.setRetryTimes( + (profitSharing.getRetryTimes() == null ? 0 : profitSharing.getRetryTimes()) + 1 + ); + profitSharing.setLastRetryTime(new Date()); + updateById(profitSharing); + } + + /** + * 处理分账响应 + * @param orderNo 订单号 + * @param response 分账响应 + */ + private void handleProfitSharingResponse(String orderNo, OrdersEntity response) { + try { + if (response == null) { + log.error("分账响应为空: orderNo={}", orderNo); + updateProfitSharingStatus(orderNo, 3); + throw new RuntimeException("分账响应为空"); + } + + OrderStatus state = response.getState(); + ProfitSharing profitSharing = getByOrderNo(orderNo); + + if (state == null) { + log.error("分账状态为空: orderNo={}", orderNo); + updateProfitSharingStatus(orderNo, 3); + throw new RuntimeException("分账状态为空"); + } + + switch (state) { + case PROCESSING: + // 处理中,更新状态并记录 + log.info("分账处理中: orderNo={}", orderNo); + updateProfitSharingStatus(orderNo, 1); + // 可以考虑添加异步任务进行后续查询 + break; + + case FINISHED: + // 分账完成,更新状态和其他相关信息 + log.info("分账成功: orderNo={}, response={}", orderNo, response); + profitSharing.setStatus(2); + profitSharing.setFinishTime(new Date()); + profitSharing.setOrderId(response.getOrderId()); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + + // 记录分账结果详情 + recordProfitSharingResult(orderNo, response); + break; + + default: + // 未知状态 + log.error("未知的分账状态: orderNo={}, state={}", orderNo, state); + updateProfitSharingStatus(orderNo, 3); + throw new RuntimeException("未知的分账状态:" + state); + } + + } catch (Exception e) { + log.error("处理分账响应失败: orderNo={}, response={}", orderNo, response, e); + updateProfitSharingStatus(orderNo, 3); + throw new RuntimeException("处理分账响应失败: " + e.getMessage(), e); + } + } + + /** + * 记录分账结果详情 + */ + private void recordProfitSharingResult(String orderNo, OrdersEntity response) { + try { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing != null) { + // 更新分账接收方信息 + List receivers = response.getReceivers(); + if (receivers != null && !receivers.isEmpty()) { + OrderReceiverDetail receiver = receivers.get(0); + profitSharing.setReceiverAmount(receiver.getAmount()); + profitSharing.setFinishTime(new Date()); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + } + } + } catch (Exception e) { + log.error("记录分账结果详情失败: orderNo={}", orderNo, e); + // 这里只记录日志,不抛出异常,避免影响主流程 + } + } + + @Override + public ProfitSharing getByOrderNo(String orderNo) { + return getOne(new LambdaQueryWrapper() + .eq(ProfitSharing::getOrderNo, orderNo)); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updateProfitSharingStatus(String orderNo, Integer status) { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing != null) { + profitSharing.setStatus(status); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + } + } + + @Override + public PageResult findList(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.orderByDesc(ProfitSharing::getCreateTime); + + Page result = baseMapper.selectPage(page, wrapper); + return PageResult.builder().data(result.getRecords()).count(result.getTotal()).build(); + } + + private String generateProfitSharingNo() { + return "PS" + System.currentTimeMillis() + RandomStringUtils.randomNumeric(4); + } + + private void validatePayeeAccount(QrCode qrCode) { + if (qrCode.getPayeeAccount() == null) { + throw new IllegalArgumentException("分账账号不能为空"); + } + if (qrCode.getPayeeStatus() != 1) { + throw new IllegalArgumentException("分账账号未验证或验证失败"); + } + } + + private long calculateQrCodeAmount(long totalAmount, BigDecimal profitRate) { + try { + return profitRate.multiply(new BigDecimal(totalAmount)) + .divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP) + .longValue(); + } catch (Exception e) { + log.error("计算分账金额失败: totalAmount={}, profitRate={}", totalAmount, profitRate, e); + throw new RuntimeException("计算分账金额失败", e); + } + } + + // 查询分账结果 + public OrdersEntity queryProfitSharingResult(String outOrderNo, String transactionId) { + try { + QueryOrderRequest request = new QueryOrderRequest(); + request.setOutOrderNo(outOrderNo); + request.setTransactionId(transactionId); + ProfitSharing profitSharing = getByOrderNo(outOrderNo); + return wxPayConfigFactory.createProfitsharingService(profitSharing.getTenantId()).queryOrder(request); + } catch (Exception e) { + log.error("查询分账结果失败: outOrderNo={}, transactionId={}", outOrderNo, transactionId, e); + throw new RuntimeException("查询分账结果失败", e); + } + } + + @Override + public ProfitSharingResult queryProfitSharingStatus(String orderNo) { + try { + // 1. 获取分账记录 + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing == null) { + throw new IllegalArgumentException("分账记录不存在: " + orderNo); + } + + // 2. 如果分账已完成,直接返回结果 + if (profitSharing.getStatus() == ProfitSharingStatusEnum.SUCCESS.getCode()) { + return buildProfitSharingResult(profitSharing, null); + } + + // 3. 查询微信分账结果 + OrdersEntity response = null; + if (profitSharing.getTransactionId() != null && profitSharing.getOutOrderNo() != null) { + QueryOrderRequest request = new QueryOrderRequest(); + request.setOutOrderNo(profitSharing.getOutOrderNo()); + request.setTransactionId(profitSharing.getTransactionId()); + response = wxPayConfigFactory.createProfitsharingService(profitSharing.getTenantId()).queryOrder(request); + } + + // 4. 构建返回结果 + return buildProfitSharingResult(profitSharing, response); + + } catch (Exception e) { + log.error("查询分账状态失败: orderNo={}", orderNo, e); + throw new RuntimeException("查询分账状态失败", e); + } + } + + private ProfitSharingResult buildProfitSharingResult(ProfitSharing profitSharing, OrdersEntity response) { + ProfitSharingResult result = ProfitSharingResult.builder() + .orderNo(profitSharing.getOrderNo()) + .transactionId(profitSharing.getTransactionId()) + .profitSharingId(profitSharing.getProfitSharingId()) + .status(profitSharing.getStatus()) + .totalAmount(profitSharing.getTotalAmount()) + .receiverAmount(profitSharing.getReceiverAmount()) + .finishTime(profitSharing.getFinishTime()) + .failReason(profitSharing.getFailReason()) + .build(); + + // 如果有微信返回的分账结果,添加接收方详情 + if (response != null && response.getReceivers() != null) { + List receivers = response.getReceivers().stream() + .map(this::convertToReceiverResult) + .collect(Collectors.toList()); + result.setReceivers(receivers); + } + + return result; + } + + private ProfitSharingResult.ReceiverResult convertToReceiverResult(OrderReceiverDetail detail) { + return ProfitSharingResult.ReceiverResult.builder() + .type(String.valueOf(detail.getType())) + .account(detail.getAccount()) + .amount(detail.getAmount()) + .description(detail.getDescription()) + .result(detail.getResult().toString()) + .failReason(detail.getFailReason().toString()) + .detailId(detail.getDetailId()) + .build(); + } + + private void handleProfitSharingError(String orderNo, Exception e) { + try { + log.error("分账执行失败: orderNo={}", orderNo, e); + + // 1. 获取分账记录 + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing == null) { + return; + } + + // 2. 更新分账状态为失败 + profitSharing.setStatus(ProfitSharingStatusEnum.FAILED.getCode()); + profitSharing.setFailReason(getErrorMessage(e)); + profitSharing.setUpdateTime(new Date()); + + // 3. 保存更新 + updateById(profitSharing); + + // 4. 如果开启了自动重试且满足重试条件,则添加重试任务 + if (shouldRetry(profitSharing)) { + scheduleRetry(orderNo); + } + + // 5. 发送告警通知(如果需要) + sendAlertNotification(profitSharing, e); + + } catch (Exception ex) { + log.error("处理分账错误时发生异常", ex); + } + } + + private boolean shouldRetry(ProfitSharing profitSharing) { + return profitSharingProperties.isEnabled() + && profitSharing.canRetry() + && !isSystemError(profitSharing.getFailReason()); + } + + private boolean isSystemError(String failReason) { + // 系统级错误不进行重试,例如:参数错误、签名错误等 + if (failReason == null) { + return false; + } + return failReason.contains("PARAM_ERROR") + || failReason.contains("SIGN_ERROR") + || failReason.contains("INVALID_REQUEST"); + } + + @Async + protected void scheduleRetry(String orderNo) { + try { + // 延迟指定时间后执行重试 + Thread.sleep(profitSharingProperties.getRetryInterval()); + retryFailedProfitSharing(orderNo); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.error("重试任务被中断: orderNo={}", orderNo); + } + } + + private void sendAlertNotification(ProfitSharing profitSharing, Exception e) { + try { + // 这里实现告警通知逻辑,例如: + // 1. 发送邮件 + // 2. 发送钉钉消息 + // 3. 发送微信消息 + // 4. 写入告警日志 + + String alertMessage = String.format( + "分账失败告警\n订单号:%s\n失败原因:%s\n重试次数:%d\n异常信息:%s", + profitSharing.getOrderNo(), + profitSharing.getFailReason(), + profitSharing.getRetryTimes(), + e.getMessage() + ); + + log.warn(alertMessage); + + // TODO: 实现具体的告警通知逻辑 + + } catch (Exception ex) { + log.error("发送告警通知失败", ex); + } + } + + /** + * 构建分账请求 + */ + private CreateOrderRequest buildProfitSharingRequest(ProfitSharing profitSharing) { + try { + // 1. 创建分账请求对象 + CreateOrderRequest request = new CreateOrderRequest(); + + // 2. 设置基本信息 + request.setAppid(wechatConfigService.getConfig("PAY",profitSharing.getTenantId()).getAppId()); + request.setTransactionId(profitSharing.getTransactionId()); + request.setOutOrderNo(generateProfitSharingNo()); + + // 3. 设置分账接收方列表 + List receivers = new ArrayList<>(); + CreateOrderReceiver receiver = new CreateOrderReceiver(); + + // 4. 设置接收方信息 + receiver.setType(profitSharing.getPayeeType()); + receiver.setAccount(profitSharing.getPayeeAccount()); + receiver.setAmount(profitSharing.getQrCodeAmount()); + receiver.setDescription("二维码分账"); + + receivers.add(receiver); + request.setReceivers(receivers); + + // 5. 保存分账请求号 + profitSharing.setOutOrderNo(request.getOutOrderNo()); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + + log.info("构建分账请求: orderNo={}, request={}", profitSharing.getOrderNo(), request); + return request; + + } catch (Exception e) { + log.error("构建分账请求失败: profitSharing={}", profitSharing, e); + throw new BusinessException("构建分账请求失败: " + e.getMessage()); + } + } + + /** + * 验证分账请求参数 + */ + private void validateProfitSharingRequest(ProfitSharing profitSharing) { + if (StringUtils.isEmpty(profitSharing.getTransactionId())) { + throw new BusinessException("支付交易号不能为空"); + } + + if (StringUtils.isEmpty(profitSharing.getPayeeAccount())) { + throw new BusinessException("分账接收方账号不能为空"); + } + + if (StringUtils.isEmpty(profitSharing.getPayeeType())) { + throw new BusinessException("分账接收方类型不能为空"); + } + + if (profitSharing.getQrCodeAmount() == null || profitSharing.getQrCodeAmount() <= 0) { + throw new BusinessException("分账金额必须大于0"); + } + + // 验证金额不超过订单总额 + if (profitSharing.getQrCodeAmount() > profitSharing.getTotalAmount()) { + throw new BusinessException("分账金额不能超过订单总额"); + } + } + + @Override + public ProfitSharingStatisticsVO getStatistics() { + try { + // 1. 获取总体统计 + Map totalStats = profitSharingMapper.getTotalStatistics(); + + // 2. 获取最近30天的数据 + Date startTime = DateUtils.addDays(new Date(), -30); + + // 3. 获取趋势数据 + List> dailyTrend = profitSharingMapper.getDailyAmountTrend(startTime); + List amountTrend = convertToTrendData(dailyTrend); + + // 4. 获取成功率数据 + List> dailyRate = profitSharingMapper.getDailySuccessRate(startTime); + List successRate = convertToRateData(dailyRate); + + // 5. 构建返回数据 + return ProfitSharingStatisticsVO.builder() + .totalCount(getLongValue(totalStats, "total_count")) + .successCount(getLongValue(totalStats, "success_count")) + .failCount(getLongValue(totalStats, "fail_count")) + .totalAmount(getLongValue(totalStats, "total_amount")) + .amountTrend(amountTrend) + .successRate(successRate) + .build(); + + } catch (Exception e) { + log.error("获取分账统计数据失败", e); + throw new BusinessException("获取统计数据失败"); + } + } + + private List convertToTrendData(List> dailyTrend) { + return dailyTrend.stream() + .map(map -> ProfitSharingStatisticsVO.TrendData.builder() + .date(String.valueOf(map.get("date"))) + .type(String.valueOf(map.get("type"))) + .amount(getLongValue(map, "amount")) + .build()) + .collect(Collectors.toList()); + } + + private List convertToRateData(List> dailyRate) { + return dailyRate.stream() + .map(map -> ProfitSharingStatisticsVO.RateData.builder() + .date(String.valueOf(map.get("date"))) + .type(String.valueOf(map.get("type"))) + .value(getDoubleValue(map, "value")) + .build()) + .collect(Collectors.toList()); + } + + private Long getLongValue(Map map, String key) { + Object value = map.get(key); + return value == null ? 0L : Long.valueOf(String.valueOf(value)); + } + + private Double getDoubleValue(Map map, String key) { + Object value = map.get(key); + return value == null ? 0.0 : Double.valueOf(String.valueOf(value)); + } + + /** + * 检查是否开启分润 + */ + private boolean isEnableProfit(QrCode qrCode) { + return qrCode != null && + Integer.valueOf(1).equals(qrCode.getEnableProfit()) && + qrCode.getPayeeStatus() != null && + qrCode.getPayeeStatus() == 1; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/QrCodeServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/QrCodeServiceImpl.java new file mode 100644 index 00000000..d6a84862 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/QrCodeServiceImpl.java @@ -0,0 +1,54 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.QrCodeMapper; +import com.central.order.model.QrCode; +import com.central.order.service.IQrCodeService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class QrCodeServiceImpl extends SuperServiceImpl implements IQrCodeService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public boolean createQrCode(QrCode qrCode) { + int result = baseMapper.insert(qrCode); + if(result > 0){ + return true; + } + return false; + } + + @Override + public QrCode getByCodeId(String codeId) { + return baseMapper.getByCodeId(codeId); + } + + + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/RefundServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/RefundServiceImpl.java new file mode 100644 index 00000000..5265940f --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/RefundServiceImpl.java @@ -0,0 +1,52 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.RefundMapper; +import com.central.order.model.Refund; +import com.central.order.service.IRefundService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +@Primary +public class RefundServiceImpl extends SuperServiceImpl implements IRefundService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public boolean createRefund(Refund refund) { + + return baseMapper.insert(refund) > 0 ? true : false; + } + + @Override + public Refund getRefundByNo(String refundNo) { + return baseMapper.selectOne(new QueryWrapper().eq("refund_no",refundNo)); + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismFileServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismFileServiceImpl.java new file mode 100644 index 00000000..8a53b5b9 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismFileServiceImpl.java @@ -0,0 +1,50 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.TourismFileMapper; +import com.central.order.model.TourismFile; +import com.central.order.service.ITourismFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class TourismFileServiceImpl extends SuperServiceImpl implements ITourismFileService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public Result saveOrUpdateTourismFile(TourismFile tourismFile) { + boolean result = saveOrUpdate(tourismFile); + return result ? Result.succeed(tourismFile, "操作成功") : Result.failed("操作失败"); + } + + @Override + public List getByTourismId(Long id) { + return baseMapper.getByTourismId(id); + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java new file mode 100644 index 00000000..982ebcaf --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java @@ -0,0 +1,50 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.TourismMapper; +import com.central.order.model.Tourism; +import com.central.order.service.ITourismService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class TourismServiceImpl extends SuperServiceImpl implements ITourismService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public Result saveOrUpdateTourism(Tourism tourism) { + boolean result = saveOrUpdate(tourism); + return result ? Result.succeed(tourism, "操作成功") : Result.failed("操作失败"); + } + + @Override + public Tourism getTourismById(Long id) { + return baseMapper.getTourismById(id); + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/VideoEditServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/VideoEditServiceImpl.java new file mode 100644 index 00000000..445798f5 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/VideoEditServiceImpl.java @@ -0,0 +1,214 @@ +package com.central.order.service.impl; + +import com.central.common.exception.BusinessException; +import com.central.common.model.FileInfo; +import com.central.common.model.SysUser; +import com.central.order.constants.EditTaskStatus; +import com.central.order.feign.FileCenterService; +import com.central.order.feign.UserCenterService; +import com.central.order.model.EditTask; +import com.central.order.model.Order; +import com.central.order.model.OrderFile; +import com.central.order.model.Tourism; +import com.central.order.model.dto.VideoEditStatus; +import com.central.order.service.*; +import com.central.order.util.DateUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.List; + +/** + * 视频编辑服务实现类 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class VideoEditServiceImpl implements IVideoEditService { + @Autowired + private IMediaService mediaService; + @Autowired + private IEditTaskService editTaskService; + @Autowired + private IOrderFileService orderFileService; + @Autowired + private FileCenterService fileCenterService; + @Autowired + private IOrderService orderService; + @Autowired + private UserCenterService userCenterService; + @Autowired + private ITourismService tourismService; + @Autowired + private WxMiniSubscribeService wxMiniSubscribeService; + + @Override + @Transactional(rollbackFor = Exception.class) + public String submitEditTask(String orderNo, List orderFiles) { + try { + // 提交智能一键成片任务 + String jobId = mediaService.submitEditTask(orderNo, orderFiles); + + // 更新任务状态 + editTaskService.updateTaskStatus(jobId, EditTaskStatus.PROCESSING, null); + + return jobId; + } catch (Exception e) { + log.error("提交视频编辑任务失败: orderNo={}", orderNo, e); + throw new BusinessException("提交编辑任务失败: " + e.getMessage()); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public VideoEditStatus handleEditStatus(String jobId) { + try { + // 1. 获取任务信息 + EditTask task = editTaskService.getByJobId(jobId); + if (task == null) { + throw new BusinessException("任务不存在"); + } + + // 2. 获取任务状态 + String status = mediaService.getTaskStatus(jobId); + VideoEditStatus editStatus = VideoEditStatus.fromCode(status); + + // 3. 处理不同状态 + switch (editStatus) { + case SUCCESS: + handleTaskSuccess(jobId, task); + break; + case FAIL: + handleTaskFailed(jobId, task); + break; + case RUNNING: + // 继续处理中,不需要更新 + break; + default: + log.warn("未知的任务状态: jobId={}, status={}", jobId, status); + } + + return editStatus; + } catch (Exception e) { + log.error("查询任务状态失败: jobId={}", jobId, e); + throw new BusinessException("查询任务状态失败: " + e.getMessage()); + } + } + + /** + * 处理任务成功 + */ + private void handleTaskSuccess(String jobId, EditTask task) { + try { + // 1. 获取输出URL + String outputUrl = mediaService.getTaskResult(jobId); + if (outputUrl == null || outputUrl.isEmpty()) { + throw new BusinessException("获取输出URL失败"); + } + + // 2. 保存视频文件记录 + saveOutputVideo(task.getOrderSn(), outputUrl); + + // 3. 更新任务状态 + editTaskService.updateTaskStatus(jobId, EditTaskStatus.COMPLETED, null); + + log.info("视频编辑任务处理完成: jobId={}, orderNo={}, outputUrl={}", + jobId, task.getOrderSn(), outputUrl); + + // 发送小程序通知 + notifyUser(task.getUserId(),task.getOrderSn()); + + } catch (Exception e) { + log.error("处理任务成功状态失败: jobId={}", jobId, e); + throw new BusinessException("处理任务成功状态失败: " + e.getMessage()); + } + } + + /** + * 处理任务失败 + */ + private void handleTaskFailed(String jobId, EditTask task) { + try { + editTaskService.updateTaskStatus(jobId, EditTaskStatus.FAILED, "任务处理失败"); + log.warn("视频编辑任务失败: jobId={}, orderNo={}", jobId, task.getOrderSn()); + } catch (Exception e) { + log.error("处理任务失败状态失败: jobId={}", jobId, e); + throw new BusinessException("处理任务失败状态失败: " + e.getMessage()); + } + } + + /** + * 保存输出视频信息 + */ + private void saveOutputVideo(String orderNo, String outputUrl) { + try { + FileInfo fileInfo = fileCenterService.creatFileInfo(outputUrl); + Order order = orderService.getOrderByNumber(orderNo); + + OrderFile orderFile = new OrderFile(); + orderFile.setFileId(fileInfo.getId()); + orderFile.setOrderNo(orderNo); + orderFile.setFileType("video/mp4"); + orderFile.setFilePath(extractFilePath(outputUrl)); + orderFile.setUserId(order.getUserId()); + orderFile.setTourismId(order.getTourismId()); + orderFileService.save(orderFile); + } catch (Exception e) { + log.error("保存输出视频信息失败: orderNo={}, outputUrl={}", orderNo, outputUrl, e); + throw new BusinessException("保存视频信息失败: " + e.getMessage()); + } + } + + /** + * 从URL提取文件路径 + */ + private String extractFilePath(String outputUrl) { + try { + // 假设URL格式为: https://bucket.endpoint/output/xxx.mp4 + String[] parts = outputUrl.split("/"); + return String.join("/", Arrays.copyOfRange(parts, 3, parts.length)); + } catch (Exception e) { + log.error("提取文件路径失败: outputUrl={}", outputUrl, e); + throw new BusinessException("提取文件路径失败: " + e.getMessage()); + } + } + + private void notifyUser(Long userId,String orderNo) { + try { + // 1. 获取用户信息 + SysUser user = userCenterService.findUserById(userId); + if (user == null || user.getOpenId() == null) { + log.warn("未找到用户或用户未绑定小程序openId,无法发送成片完成通知: userId={}", userId); + return; + } + + // 2. 获取任务和订单信息 + // 假设 message 里包含订单号或任务名,实际可根据 EditTask 查找 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null) { + log.warn("未找到订单信息,无法发送成片完成通知: orderNo={}", orderNo); + return; + } + + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + String result = "视频已生成请查阅"; + String pageUrl = "pages/album/album"; + wxMiniSubscribeService.sendServiceProcessMsg( + user.getOpenId(), + tourism.getTourismName(), + result, + orderNo, + DateUtils.sdf.format(order.getPayTime()), + "", + pageUrl + ); + log.info("已发送一键成片完成通知: userId={}, openId={}, orderNo={}", userId, user.getOpenId(), orderNo); + } catch (Exception e) { + log.error("发送一键成片完成通知失败: userId={}, message={}", userId, orderNo, e); + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/VideoTemplateServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/VideoTemplateServiceImpl.java new file mode 100644 index 00000000..f6c7b1aa --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/VideoTemplateServiceImpl.java @@ -0,0 +1,82 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.VideoTemplateMapper; +import com.central.order.model.VideoTemplate; +import com.central.order.service.IVideoTemplateService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Date; +import java.util.Map; + +@Slf4j +@Service +public class VideoTemplateServiceImpl extends SuperServiceImpl implements IVideoTemplateService { + + @Override + public PageResult findList(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(VideoTemplate::getIsDel, 0) + .orderByDesc(VideoTemplate::getCreateTime); + + Page result = baseMapper.selectPage(page, wrapper); + return PageResult.builder().data(result.getRecords()).count(result.getTotal()).build(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean saveTemplate(VideoTemplate template) { + template.setCreateTime(new Date()); + template.setUpdateTime(new Date()); + template.setIsDel(0); + return save(template); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateTemplate(VideoTemplate template) { + template.setUpdateTime(new Date()); + return updateById(template); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean deleteTemplate(Long id) { + VideoTemplate template = getById(id); + if (template != null) { + template.setIsDel(1); + template.setUpdateTime(new Date()); + return updateById(template); + } + return false; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateStatus(Long id, Integer status) { + VideoTemplate template = getById(id); + if (template != null) { + template.setStatus(status); + template.setUpdateTime(new Date()); + return updateById(template); + } + return false; + } + + @Override + public VideoTemplate getActiveTemplate() { + return getOne(new LambdaQueryWrapper() + .eq(VideoTemplate::getStatus, 1) + .eq(VideoTemplate::getIsDel, 0) + .orderByDesc(VideoTemplate::getCreateTime) + .last("LIMIT 1")); + } +} \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxAccessTokenServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxAccessTokenServiceImpl.java new file mode 100644 index 00000000..e4b10f44 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxAccessTokenServiceImpl.java @@ -0,0 +1,106 @@ +package com.central.order.service.impl; + +import com.central.common.exception.BusinessException; +import com.central.order.service.IWxAccessTokenService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import me.chanjar.weixin.common.error.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestClientException; + +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Service +@RequiredArgsConstructor +public class WxAccessTokenServiceImpl implements IWxAccessTokenService { + + @Autowired + private WxMpService wxMpService; + @Autowired + private StringRedisTemplate redisTemplate; + private static final String ACCESS_TOKEN_KEY = "wx:access_token"; + private static final String ACCESS_TOKEN_LOCK_KEY = "wx:access_token:lock"; + + @Override + public String getAccessToken() { + // 先从Redis获取 + String accessToken = redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY); + if (StringUtils.isNotBlank(accessToken)) { + return accessToken; + } + + // 获取分布式锁 + String lockValue = UUID.randomUUID().toString(); + boolean locked = redisTemplate.opsForValue() + .setIfAbsent(ACCESS_TOKEN_LOCK_KEY, lockValue, 30, TimeUnit.SECONDS); + + if (!locked) { + // 如果没有获取到锁,等待100ms后重试 + try { + Thread.sleep(100); + return getAccessToken(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new BusinessException("获取access_token被中断"); + } + } + + try { + // 双重检查 + accessToken = redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY); + if (StringUtils.isNotBlank(accessToken)) { + return accessToken; + } + + // 刷新token + return refreshAccessToken(); + } finally { + // 释放锁 + if (lockValue.equals(redisTemplate.opsForValue().get(ACCESS_TOKEN_LOCK_KEY))) { + redisTemplate.delete(ACCESS_TOKEN_LOCK_KEY); + } + } + } + + @Retryable( + value = {WxErrorException.class, RestClientException.class}, + maxAttempts = 3, + backoff = @Backoff(delay = 2000, multiplier = 2) + ) + public String refreshAccessToken() { + try { + log.info("开始刷新access_token"); + String newToken = wxMpService.getAccessToken(); + + // 设置到Redis,有效期设置为110分钟(微信token有效期120分钟) + redisTemplate.opsForValue().set(ACCESS_TOKEN_KEY, newToken, 110, TimeUnit.MINUTES); + + log.info("刷新access_token成功"); + return newToken; + } catch (Exception e) { + log.error("刷新access_token失败", e); + throw new BusinessException("刷新access_token失败:" + e.getMessage()); + } + } + + @Recover + public String recover(Exception e) { + log.error("刷新access_token重试耗尽", e); + // 发送告警通知 + sendAlertNotification("刷新access_token失败,请检查网络和配置"); + throw new BusinessException("刷新access_token失败,请稍后重试"); + } + + private void sendAlertNotification(String message) { + // TODO: 实现告警通知逻辑 + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxMessageRecordServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxMessageRecordServiceImpl.java new file mode 100644 index 00000000..2d1e833c --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxMessageRecordServiceImpl.java @@ -0,0 +1,112 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.central.common.model.PageResult; +import com.central.order.enums.CommonStatus; +import com.central.order.mapper.WxMessageRecordMapper; +import com.central.order.model.WxMessageRecord; +import com.central.order.service.IWxMessageRecordService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class WxMessageRecordServiceImpl extends ServiceImpl implements IWxMessageRecordService { + + @Override + public PageResult findRecords(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page", 1), + MapUtils.getInteger(params, "limit", 10)); + + QueryWrapper wrapper = new QueryWrapper<>(); + + // 添加查询条件 + String openId = MapUtils.getString(params, "openId"); + if (openId != null) { + wrapper.eq("open_id", openId); + } + + Integer status = MapUtils.getInteger(params, "status"); + if (status != null) { + wrapper.eq("status", status); + } + + String startTime = MapUtils.getString(params, "startTime"); + if (startTime != null) { + wrapper.ge("create_time", startTime); + } + + String endTime = MapUtils.getString(params, "endTime"); + if (endTime != null) { + wrapper.le("create_time", endTime); + } + + wrapper.orderByDesc("create_time"); + + Page recordPage = this.page(page, wrapper); + return PageResult.builder() + .data(recordPage.getRecords()) + .count(recordPage.getTotal()) + .build(); + } + + @Override + public void saveRecord(String openId, String templateId, String content, String msgId, Integer status) { + WxMessageRecord record = WxMessageRecord.builder() + .openId(openId) + .templateId(templateId) + .content(content) + .msgId(msgId) + .status(status) + .build(); + this.save(record); + } + + @Override + public void updateStatus(String msgId, Integer status, String errorMsg) { + WxMessageRecord record = new WxMessageRecord(); + record.setStatus(status); + record.setErrorMsg(errorMsg); + + this.update(record, new QueryWrapper() + .eq("msg_id", msgId)); + } + + @Override + public Map getStatistics(LocalDateTime startTime, LocalDateTime endTime) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.between("create_time", startTime, endTime); + + Map statistics = new HashMap<>(); + + // 总发送量 + long total = this.count(wrapper); + statistics.put("total", total); + + // 发送成功量 + long success = this.count(wrapper.clone().eq("status", CommonStatus.ENABLE.getId())); + statistics.put("success", success); + + // 发送失败量 + long failed = this.count(wrapper.clone().eq("status", CommonStatus.UNABLE.getId())); + statistics.put("failed", failed); + + return statistics; + } + + @Override + public List getFailedRecords() { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("status", CommonStatus.UNABLE.getId()) + .orderByDesc("create_time"); + return this.list(wrapper); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxMiniSubscribeServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxMiniSubscribeServiceImpl.java new file mode 100644 index 00000000..f014dc0b --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxMiniSubscribeServiceImpl.java @@ -0,0 +1,83 @@ +package com.central.order.service.impl; + +import cn.binarywang.wx.miniapp.api.WxMaService; +import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage; +import com.central.order.service.WxMiniSubscribeService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + + +@Slf4j +@Service +public class WxMiniSubscribeServiceImpl implements WxMiniSubscribeService { + + @Value("${wx.mini.template.pay-success}") + private String templateId; + + @Value("${wx.mini.template.service-process}") + private String serviceProcessTemplateId; + + @Autowired + private WxMaService wxMaService; + + @Override + public void sendPaySuccessMsg(String openId, String orderName, String orderNo, String tip, String amount, String orderTime) { + try { + WxMaSubscribeMessage msg = new WxMaSubscribeMessage(); + msg.setToUser(openId); + msg.setTemplateId(templateId); + msg.setPage("pages/task/task"); // 可选跳转页面 + + List dataList = new ArrayList<>(); + dataList.add(new WxMaSubscribeMessage.MsgData("thing1", orderName)); // 订单名称 + dataList.add(new WxMaSubscribeMessage.MsgData("character_string2", orderNo)); // 订单编号 + dataList.add(new WxMaSubscribeMessage.MsgData("thing4", tip)); // 温馨提示 + dataList.add(new WxMaSubscribeMessage.MsgData("amount9", amount)); // 已付金额 + dataList.add(new WxMaSubscribeMessage.MsgData("time10", orderTime)); // 下单时间 + msg.setData(dataList); + + wxMaService.getSubscribeService().sendSubscribeMsg(msg); + log.info("小程序支付成功订阅消息发送成功: openId={}, orderNo={}", openId, orderNo); + } catch (Exception e) { + log.error("小程序支付成功订阅消息发送失败: openId={}, orderNo={}, error={}", openId, orderNo, e.getMessage(), e); + } + } + + @Override + public void sendActivityStartMsg(String openId, String place, String activityName, String remark, String activityNo) { + + } + + @Override + public void sendVideoEditCompleteMsg(String openId, String taskName, String orderNo, String result) { + + } + + @Override + public void sendServiceProcessMsg(String openId, String taskName, String processDesc, String orderNo, String orderTime, String result, String pageUrl) { + try { + WxMaSubscribeMessage msg = new WxMaSubscribeMessage(); + msg.setToUser(openId); + msg.setTemplateId(serviceProcessTemplateId); + msg.setPage(pageUrl); // 可选跳转页面 "pages/task/task" + + List dataList = new ArrayList<>(); + dataList.add(new WxMaSubscribeMessage.MsgData("thing1", taskName)); // 服务名称 + dataList.add(new WxMaSubscribeMessage.MsgData("thing4", processDesc)); // 服务阶段 + dataList.add(new WxMaSubscribeMessage.MsgData("character_string7", orderNo)); // 订单编号 + dataList.add(new WxMaSubscribeMessage.MsgData("time8", orderTime)); // 已付金额 + dataList.add(new WxMaSubscribeMessage.MsgData("thing6", processDesc)); // 备注 + msg.setData(dataList); + + wxMaService.getSubscribeService().sendSubscribeMsg(msg); + log.info("小程序服务进度订阅消息发送成功: openId={}, orderNo={}", openId, orderNo); + } catch (Exception e) { + log.error("小程序服务进度订阅消息发送失败: openId={}, orderNo={}, error={}", openId, orderNo, e.getMessage(), e); + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxTemplateMessageServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxTemplateMessageServiceImpl.java new file mode 100644 index 00000000..d8532de4 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxTemplateMessageServiceImpl.java @@ -0,0 +1,183 @@ +package com.central.order.service.impl; + +import com.central.common.exception.BusinessException; +import com.central.order.enums.CommonStatus; +import com.central.order.model.WxMessageRecord; +import com.central.order.service.IWxMessageRecordService; +import com.central.order.service.IWxTemplateMessageService; +import com.central.order.service.IWxUserService; +import com.central.wechat.entity.WechatConfig; +import com.central.wechat.feign.WechatConfigService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import me.chanjar.weixin.common.error.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.bean.template.WxMpTemplateData; +import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; + +@Slf4j +@Service +@RequiredArgsConstructor +public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService { + + @Autowired + private WxMpService wxMpService; + + @Autowired + private IWxUserService wxUserService; + + @Autowired + private WechatConfigService wechatConfigService; + + @Autowired + private IWxMessageRecordService wxMessageRecordService; + + @Value("${zlt.tenant.id}") + private String defaultTenantId; + + @Override + @Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2)) + public void sendPaymentSuccessNotice(String unionId, String orderNo, String tourismName, + Integer rank) { + log.info("准备发送支付成功通知: openId={}, orderNo={}, serviceName={}, amount={}, tourTime={}", + unionId, orderNo, tourismName, rank); + + // 参数验证 + if (StringUtils.isAnyBlank(unionId, orderNo, tourismName)) { + throw new BusinessException("参数不能为空"); + } + + try { + String openId = wxUserService.getMpOpenIdByUnionId(unionId); + log.info("获取到服务号openId={}", openId); + WechatConfig config = wechatConfigService.getConfig("PAY",defaultTenantId); + // 构建模板消息 + WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder() + .toUser(openId) + .templateId(config.getPaymentSuccessTemplateId()) + .data(Arrays.asList( + new WxMpTemplateData("thing2", tourismName+"提示: 您当前排在第"+rank+"位!"), + new WxMpTemplateData("time3", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))), + new WxMpTemplateData("character_string1", orderNo) +// new WxMpTemplateData("amount4", "19.90") + )) + .miniProgram(new WxMpTemplateMessage.MiniProgram( + config.getAppId(), + "pages/index/index", + true)) + .build(); + + // 发送消息并获取消息ID + String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage); + + // 记录发送结果 + log.info("模板消息发送成功: openId={}, orderNo={}, msgId={}", openId, orderNo, msgId); + + // 保存发送记录 + saveMessageRecord(openId, msgId, templateMessage,CommonStatus.ENABLE.getId()); + + } catch (WxErrorException e) { + log.error("发送模板消息失败: unionId={}, orderNo={}, errorCode={}, errorMsg={}", + unionId, orderNo, e.getError().getErrorCode(), e.getError().getErrorMsg()); + // 保存发送记录 @TODO +// saveMessageRecord(openId, msgId, templateMessage,CommonStatus.ENABLE.getId()); + throw new BusinessException("发送失败:" + e.getError().getErrorMsg()); + } + } + + private String formatDateTime(LocalDateTime dateTime) { + if (dateTime == null) { + return ""; + } + return dateTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm")); + } + + private String formatAmount(BigDecimal amount) { + if (amount == null) { + return "0.00"; + } + return amount.setScale(2, RoundingMode.HALF_UP).toString() + "元"; + } + + private void saveMessageRecord(String openId, String msgId, WxMpTemplateMessage templateMessage,Integer status) { + try { + // 1. 提取模板消息内容 + String content = extractMessageContent(templateMessage); + + // 2. 构建消息记录 + WxMessageRecord record = WxMessageRecord.builder() + .openId(openId) + .templateId(templateMessage.getTemplateId()) + .msgId(msgId) + .content(content) + .status(status) + .build(); + + // 3. 保存记录 + log.info("准备保存微信消息记录: openId={}, msgId={}, templateId={}", + openId, msgId, templateMessage.getTemplateId()); + wxMessageRecordService.save(record); + log.info("微信消息记录保存成功: msgId={}", msgId); + + } catch (Exception e) { + log.error("保存微信消息记录失败: openId={}, msgId={}, error={}", + openId, msgId, e.getMessage(), e); + // 这里选择不抛出异常,因为消息已经发送成功,记录保存失败不应影响主流程 + } + } + + /** + * 提取模板消息内容 + */ + private String extractMessageContent(WxMpTemplateMessage templateMessage) { + StringBuilder content = new StringBuilder(); + + // 提取小程序信息 + if (templateMessage.getMiniProgram() != null) { + content.append("小程序信息:") + .append("appid=").append(templateMessage.getMiniProgram().getAppid()) + .append(", path=").append(templateMessage.getMiniProgram().getPagePath()) + .append("\n"); + } + + // 提取模板数据 + if (templateMessage.getData() != null) { + content.append("模板数据:\n"); + templateMessage.getData().forEach(data -> + content.append(data.getName()) + .append("=") + .append(data.getValue()) + .append("\n") + ); + } + + // 如果内容过长,进行截断 + String result = content.toString(); + if (result.length() > 500) { // 假设数据库字段长度限制为500 + result = result.substring(0, 497) + "..."; + } + + return result; + } + + @Recover + public void recover(WxErrorException e, String openId, String orderNo, + String serviceName, BigDecimal amount, LocalDateTime tourTime) { + log.error("发送模板消息重试耗尽: openId={}, orderNo={}, error={}", + openId, orderNo, e.getMessage()); + // TODO: 实现失败处理逻辑 + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxUserServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxUserServiceImpl.java new file mode 100644 index 00000000..c1d83412 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/WxUserServiceImpl.java @@ -0,0 +1,72 @@ +package com.central.order.service.impl; + +import com.central.order.service.IWxUserService; +import lombok.extern.slf4j.Slf4j; +import me.chanjar.weixin.common.error.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.WxMpUserService; +import me.chanjar.weixin.mp.bean.result.WxMpUser; +import me.chanjar.weixin.mp.bean.result.WxMpUserList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class WxUserServiceImpl implements IWxUserService { + + @Autowired + private WxMpService wxMpService; + + @Override + @Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 2)) + public String getMpOpenIdByUnionId(String targetUnionId) { + try { + log.info("开始查找 unionId: {} 对应的 openId", targetUnionId); + + WxMpUserService userService = wxMpService.getUserService(); + String nextOpenId = null; + + do { + // 获取关注者列表 + WxMpUserList userList = userService.userList(nextOpenId); + if (userList == null || userList.getCount() == 0) { + log.warn("未找到关注用户"); + break; + } + + // 批量获取用户信息 + for (String openId : userList.getOpenids()) { + try { + WxMpUser userInfo = userService.userInfo(openId); + if (targetUnionId.equals(userInfo.getUnionId())) { + log.info("找到匹配的 openId: {} 对应的 unionId: {}", openId, targetUnionId); + return openId; + } + } catch (WxErrorException e) { + log.warn("获取用户 {} 信息失败: {}", openId, e.getMessage()); + continue; // 单个用户获取失败继续处理下一个 + } + } + + nextOpenId = userList.getNextOpenid(); + } while (nextOpenId != null && !nextOpenId.isEmpty()); + + log.warn("未找到 unionId: {} 对应的 openId", targetUnionId); + return null; + + } catch (WxErrorException e) { + log.error("获取 MP openId 失败,unionId: {},错误: {}", targetUnionId, e.getMessage(), e); + throw new RuntimeException("获取 MP openId 失败", e); + } + } + + @Recover + public String recover(Exception e, String targetUnionId) { + log.error("获取 MP openId 重试耗尽,unionId: {},最终错误: {}", targetUnionId, e.getMessage()); + // 可以在这里添加告警通知 + return null; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/ContentTypeUtil.java b/zlt-business/order-center/src/main/java/com/central/order/util/ContentTypeUtil.java new file mode 100644 index 00000000..4f298455 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/ContentTypeUtil.java @@ -0,0 +1,29 @@ +package com.central.order.util; + +import com.central.order.enums.FileType; + +public class ContentTypeUtil { + + /** + * 根据 URL 的文件扩展名获取对应的 contentType + * + * @param url 文件的 URL + * @return 包含 contentType 的 Map,如果 URL 为空或不包含支持的扩展名,返回空的 Map + */ + public static String getContentTypeFromUrl(String url) { + + if (url != null && !url.isEmpty()) { + // 获取文件扩展名 + int lastDotIndex = url.lastIndexOf('.'); + if (lastDotIndex != -1) { + String extension = url.substring(lastDotIndex); + FileType fileType = FileType.fromExtension(extension); + if (fileType != null) { + return fileType.getContentType(); + } + } + } + + return FileType.JPEG.getContentType(); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/DateUtils.java b/zlt-business/order-center/src/main/java/com/central/order/util/DateUtils.java new file mode 100644 index 00000000..6e18733e --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/DateUtils.java @@ -0,0 +1,77 @@ +package com.central.order.util; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * + * 时间工具类 + * @author lsl + * @date 2025-03-10 + */ +public class DateUtils { + + public final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + public final static int INTERNAL = 10; + + public static boolean isWithinFiveMinutes(Date start, Date end) { + // 计算时间差(秒) + long secondsDifference = java.time.Duration.between(start.toInstant(), end.toInstant()).getSeconds(); + // 将时间差转换为分钟 + long minutesDifference = secondsDifference / 60; + // 判断时间差是否不超过 5 分钟 + return minutesDifference <= INTERNAL; + } + + public static boolean isWithinMinutes(Date start, Date end, int minutes) { + // 计算时间差(秒) + long secondsDifference = java.time.Duration.between(start.toInstant(), end.toInstant()).getSeconds(); + // 将时间差转换为分钟 + long minutesDifference = secondsDifference / 60; + // 判断时间差是否不超过 5 分钟 + return minutesDifference <= minutes; + } + + public static boolean isWithinMinutesByNow(Date start, int minutes) { + // 计算时间差(秒) + long secondsDifference = java.time.Duration.between(start.toInstant(), new Date().toInstant()).getSeconds(); + // 将时间差转换为分钟 + long minutesDifference = secondsDifference / 60; + // 判断时间差是否不超过 5 分钟 + return minutesDifference <= minutes; + } + + public static boolean isWithinFiveMinutesByNow(Date start) { + // 计算时间差(秒) + long secondsDifference = java.time.Duration.between(start.toInstant(), new Date().toInstant()).getSeconds(); + // 将时间差转换为分钟 + long minutesDifference = secondsDifference / 60; + // 判断时间差是否不超过 5 分钟 + return minutesDifference <= INTERNAL; + } + + // 获取当天的起始时间(0点0分0秒) + public static Date getStartOfDay(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + date = sdf.parse(sdf.format(date)); + } catch (Exception e) { + e.printStackTrace(); + } + return date; + } + + // 获取当天的结束时间(23点59分59秒) + public static Date getEndOfDay(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + date = sdf.parse(sdf.format(date)); + date.setTime(date.getTime() + 24 * 60 * 60 * 1000 - 1); + } catch (Exception e) { + e.printStackTrace(); + } + return date; + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/ExceptionUtils.java b/zlt-business/order-center/src/main/java/com/central/order/util/ExceptionUtils.java new file mode 100644 index 00000000..5811aa03 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/ExceptionUtils.java @@ -0,0 +1,51 @@ +package com.central.order.util; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.util.StringUtils; + +@Slf4j +public class ExceptionUtils { + + /** + * 获取异常的根本原因 + */ + public static String getRootCauseMessage(Throwable throwable) { + Throwable rootCause = getRootCause(throwable); + return rootCause.getMessage(); + } + + /** + * 获取异常的根本原因对象 + */ + public static Throwable getRootCause(Throwable throwable) { + Throwable cause = throwable; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + return cause; + } + + /** + * 格式化异常信息 + */ + public static String formatErrorMessage(String message) { + if (!StringUtils.hasText(message)) { + return "未知错误"; + } + // 移除敏感信息 + message = message.replaceAll("\\{\"password\":\"[^\"]*\"\\}", "{\"password\":\"***\"}"); + // 限制长度 + return message.length() > 200 ? message.substring(0, 200) : message; + } + + /** + * 判断是否为业务异常 + */ + public static boolean isBusinessException(Throwable throwable) { + String message = getRootCauseMessage(throwable); + // 根据错误信息判断是否为业务异常 + return message.contains("PARAM_ERROR") + || message.contains("SIGN_ERROR") + || message.contains("INVALID_REQUEST"); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/HttpServletUtils.java b/zlt-business/order-center/src/main/java/com/central/order/util/HttpServletUtils.java new file mode 100644 index 00000000..3bc732b4 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/HttpServletUtils.java @@ -0,0 +1,47 @@ +package com.central.order.util; + +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +/** + *

+ * HttpServletRequest 获取请求体 + *

+ * + * @author songfayuan + * @date 2024/9/30 19:11 + */ +public class HttpServletUtils { + + /** + * 获取请求体 + * + * @param request + * @return + * @throws IOException + */ + public static String getRequestBody(HttpServletRequest request) throws IOException { + ServletInputStream stream = null; + BufferedReader reader = null; + StringBuffer sb = new StringBuffer(); + try { + stream = request.getInputStream(); + // 获取响应 + reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); + String line; + while ((line = reader.readLine()) != null) { + sb.append(line); + } + } catch (IOException e) { + throw new IOException("读取返回支付接口数据流出现异常!"); + } finally { + reader.close(); + } + return sb.toString(); + } + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/MapUtil.java b/zlt-business/order-center/src/main/java/com/central/order/util/MapUtil.java new file mode 100644 index 00000000..9ceb1c92 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/MapUtil.java @@ -0,0 +1,52 @@ +package com.central.order.util; + +import java.util.Map; + +/** + * 获取map各类型值工具类 + * @author lishilin + * @date 2020/03/12 + */ +public class MapUtil { + public static String getStrValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + return val.toString(); + } + + public static Integer getIntValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + try { + return Integer.parseInt(param.get(id).toString()); + } catch (NumberFormatException exp) { + return null; + } + } + + public static Long getLongValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + try { + return Long.parseLong(param.get(id).toString()); + } catch (NumberFormatException exp) { + return null; + } + } + + public static Object getValue(Map param, String id) { + if (null == param && null == id) { + return null; + } + if (param.containsKey(id)) { + return param.get(id); + } + return null; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/RequestUtils.java b/zlt-business/order-center/src/main/java/com/central/order/util/RequestUtils.java new file mode 100644 index 00000000..374e92e4 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/RequestUtils.java @@ -0,0 +1,119 @@ +package com.central.order.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.central.order.util.http.HeaderUtils; +import com.central.order.util.http.HttpRequest; +import com.central.order.util.http.Response; +import com.central.order.util.http.SimpleHttpRequest; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.Map; + +/** + * @author LSL + */ +@Slf4j +@Component +public class RequestUtils { + + @Autowired + private HeaderUtils headerUtils; + + /** + * 获取post请求result + * @param url 请求url + * @param jsonObject 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, JSONObject jsonObject) throws IOException { + System.out.println(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(jsonObject.toJSONString())); + request.requestBody(jsonObject.toJSONString()); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param param 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, Map param) throws IOException { + System.out.println(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param body 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, String body) throws IOException { + System.out.println(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(body)); + request.requestBody(body); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + System.out.println(result); + return result; + } + + /** + * @param url 请求url + * @param map 请求参数map + * @return + * @throws IOException + */ + public Map getGetRequestResultMap(String url,Map map) throws IOException { + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfParams(map)); + + Response response = request.get(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param param 请求参数 + * @return + * @throws IOException + */ + public Map getThirdPartyPostRequestResultMap(String url, Map param) { + log.info("url:{} , {}",url,param); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + Response response; + Map result = null; + try { + response = request.post(); + result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + } catch (IOException e) { + log.info("查询异常:{}",e.getMessage()); + e.printStackTrace(); + } +// log.info("获取post请求result结果:{}" ,JSON.toJSONString(result)); + return result; + } + + +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/StringUtils.java b/zlt-business/order-center/src/main/java/com/central/order/util/StringUtils.java new file mode 100644 index 00000000..e30b7a57 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/StringUtils.java @@ -0,0 +1,29 @@ +package com.central.order.util; + +/** + * 字符串处理 + * @date + * @author lsl + */ +public class StringUtils { + + public static String fenToYuan(String orderAmountStr) { + if (orderAmountStr != null && !orderAmountStr.isEmpty()) { + StringBuilder result = new StringBuilder(); + int length = orderAmountStr.length(); + if (length >= 3) { + // 字符串长度大于等于 3,正常插入小数点 + result.append(orderAmountStr, 0, length - 2).append(".").append(orderAmountStr.substring(length - 2)); + } else if (length == 2) { + // 字符串长度为 2,前面补 0 + result.append("0.").append(orderAmountStr); + } else { + // 字符串长度为 1,前面补 0 + result.append("0.0").append(orderAmountStr); + } + return result.toString() + "元"; + } else { + return "0.00元"; + } + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/Utils.java b/zlt-business/order-center/src/main/java/com/central/order/util/Utils.java new file mode 100644 index 00000000..72528f12 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/Utils.java @@ -0,0 +1,47 @@ +package com.central.order.util; + +import java.io.*; +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.Map; + +/** + * @author lishilin + * @see + * @since 2.0 + */ +public class Utils { + public static Map queryStringToMap(String queryString, String charset){ + try { + Map map = new HashMap<>(); + + String[] decode = URLDecoder.decode(queryString,charset).split("&"); + for (String keyValue : decode) { + String[] kv = keyValue.split("[=]",2); + map.put(kv.length>1?kv[1]:"",kv[0]); + } + return map; + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException(e); + } + } + + /** + * 读文件 + * + * @param file 文件 + * @return + * @throws IOException + * @throws IOException + */ + public static String readTxt(File file) throws IOException { + String s = ""; + InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"); + BufferedReader br = new BufferedReader(in); + StringBuffer content = new StringBuffer(); + while ((s = br.readLine()) != null) { + content = content.append(s); + } + return content.toString(); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/http/HeaderUtils.java b/zlt-business/order-center/src/main/java/com/central/order/util/http/HeaderUtils.java new file mode 100644 index 00000000..45a58b6e --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/http/HeaderUtils.java @@ -0,0 +1,80 @@ +package com.central.order.util.http; + +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.codec.digest.DigestUtils; +import org.springframework.stereotype.Component; + +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Collectors; + +/** + * @author lishilin + * @see + * @since 1.0 + */ +@Component +public class HeaderUtils { + +// @Value("${jetlinks.clientId}") + private String xClientId = "WFMfEGS8iHrEPRBH" ; + +// @Value("${jetlinks.secureKey}") + private String secureKey = "ihat3zHC6T7xPZYFAEnG3tExQiFANd2n" ; + public Map createHeadersOfParams(Map params) { + //时间戳 + String xTimestamp = String.valueOf(System.currentTimeMillis()); + //openApi客户端id +// String xClientId = "rN7cpmQb884W4hcH"; + //密钥 +// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; + //将参数按ASCII排序后拼接为k1=v1&k2=v2的格式 + String paramString = new TreeMap<>(params).entrySet() + .stream() + .map(e -> e.getKey().concat("=").concat(String.valueOf(e.getValue()))) + .collect(Collectors.joining("&")); + + System.out.println(paramString); + + //param+X-Timestamp+SecureKey通过MD5加密 + MessageDigest digest = DigestUtils.getMd5Digest(); + System.out.println(paramString + xTimestamp + secureKey); + digest.update(paramString.getBytes()); + digest.update(xTimestamp.getBytes()); + digest.update(secureKey.getBytes()); + + Map headers = new HashMap<>(); + headers.put("X-Sign", Hex.encodeHexString(digest.digest())); + headers.put("X-Client-Id", xClientId); + headers.put("X-Timestamp", xTimestamp); + + return headers; + } + + + public Map createHeadersOfJsonString(String jsonString) { + //时间戳 + String xTimestamp = String.valueOf(System.currentTimeMillis()); + //openApi客户端id +// String xClientId = "rN7cpmQb884W4hcH"; + //密钥 +// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; + + + //param+X-Timestamp+SecureKey通过MD5加密 + MessageDigest digest = DigestUtils.getMd5Digest(); + System.out.println(jsonString + xTimestamp + secureKey); + digest.update(jsonString.getBytes()); + digest.update(xTimestamp.getBytes()); + digest.update(secureKey.getBytes()); + + Map headers = new HashMap<>(5); + headers.put("X-Sign", Hex.encodeHexString(digest.digest())); + headers.put("X-Client-Id", xClientId); + headers.put("X-Timestamp", xTimestamp); + + return headers; + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/http/HttpRequest.java b/zlt-business/order-center/src/main/java/com/central/order/util/http/HttpRequest.java new file mode 100644 index 00000000..3a8a37f3 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/http/HttpRequest.java @@ -0,0 +1,39 @@ +package com.central.order.util.http; + +import java.io.Closeable; +import java.io.IOException; +import java.util.Map; + +/** + * @author wang + * @see + * @since 1.0 + */ +public interface HttpRequest extends Closeable { + + Response get() throws IOException; + + Response post() throws IOException; + + Response put() throws IOException; + + Response delete() throws IOException; + + Response patch() throws IOException; + + HttpRequest encode(String encode); + + HttpRequest contentType(String type); + + HttpRequest param(String name, String value); + + HttpRequest params(Map params); + + HttpRequest header(String name, String value); + + HttpRequest headers(Map headers); + + HttpRequest requestBody(String body); + + HttpRequest resultAsJsonString(); +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/http/Response.java b/zlt-business/order-center/src/main/java/com/central/order/util/http/Response.java new file mode 100644 index 00000000..1ea5d317 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/http/Response.java @@ -0,0 +1,13 @@ +package com.central.order.util.http; + +import java.io.IOException; + +/** + * @author wang + * @see + * @since 1.0 + */ +public interface Response { + + byte[] asBytes() throws IOException; +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/http/SimpleHttpRequest.java b/zlt-business/order-center/src/main/java/com/central/order/util/http/SimpleHttpRequest.java new file mode 100644 index 00000000..2844ed61 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/http/SimpleHttpRequest.java @@ -0,0 +1,184 @@ +package com.central.order.util.http; + +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.*; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author wang + * @see + * @since 1.0 + */ +public class SimpleHttpRequest implements HttpRequest { + + private Map params = new LinkedHashMap<>(); + private Map headers = new LinkedHashMap<>(); + private String url; + private String requestBody; + private String contentType; + private String encode = "utf-8"; + protected HttpClient httpClient; + + public SimpleHttpRequest(String url) { + this.url = url; + createHttpClient(); + } + + public SimpleHttpRequest(String url, HttpClient client) { + this.url = url; + this.httpClient = client; + } + + protected void createHttpClient() { + if (httpClient == null) { + HttpClientBuilder builder = HttpClientBuilder.create(); + httpClient = builder.build(); + + } + } + + @Override + public Response get() throws IOException { + String param = EntityUtils.toString(createUrlEncodedFormEntity()); + String tmpUrl = url + (url.contains("?") ? "&" : "?") + param; + HttpGet get = new HttpGet(tmpUrl); + HttpResponse response = execute(get); + return getResultValue(response); + } + + + @Override + public Response post() throws IOException { + HttpPost post = new HttpPost(url); + if (requestBody != null) + post.setEntity(new StringEntity(requestBody, ContentType.create(contentType,encode))); + else { + post.setEntity(createUrlEncodedFormEntity()); + } + HttpResponse response = execute(post); + return getResultValue(response); + } + + @Override + public Response put() throws IOException { + HttpPut put = new HttpPut(url); + if (requestBody != null) + put.setEntity(new StringEntity(requestBody, ContentType.create(contentType, encode))); + else { + + put.setEntity(createUrlEncodedFormEntity()); + } + HttpResponse response = execute(put); + return getResultValue(response); + } + + protected UrlEncodedFormEntity createUrlEncodedFormEntity() throws UnsupportedEncodingException { + List nameValuePair = params.entrySet() + .stream().map(stringStringEntry -> + new BasicNameValuePair(stringStringEntry.getKey(), String.valueOf(stringStringEntry.getValue()))) + .collect(Collectors.toList()); + return new UrlEncodedFormEntity(nameValuePair, encode); + } + + @Override + public Response delete() throws IOException { + HttpDelete delete = new HttpDelete(url); + HttpResponse response = execute(delete); + return getResultValue(response); + } + + @Override + public Response patch() throws IOException { + HttpPatch delete = new HttpPatch(url); + if (requestBody != null) + delete.setEntity(new StringEntity(requestBody, ContentType.create(contentType))); + else { + delete.setEntity(createUrlEncodedFormEntity()); + } + return getResultValue(execute(delete)); + } + + @Override + public void close() throws IOException { + if (httpClient != null && httpClient instanceof CloseableHttpClient) { + ((CloseableHttpClient) httpClient).close(); + } + } + + @Override + public HttpRequest resultAsJsonString() { + header("Accept", "application/json"); + return this; + } + + @Override + public HttpRequest requestBody(String body) { + contentType("application/json"); + this.requestBody = body; + return this; + } + + @Override + public HttpRequest encode(String encode) { + this.encode = encode; + return this; + } + + @Override + public HttpRequest contentType(String type) { + this.contentType = type; + return this; + } + + @Override + public HttpRequest param(String name, String value) { + this.params.put(name, value); + return this; + } + + @Override + public HttpRequest params(Map params) { + this.params.putAll(params); + return this; + } + + @Override + public HttpRequest header(String name, String value) { + this.headers.put(name, value); + return this; + } + + @Override + public HttpRequest headers(Map header) { + this.headers.putAll(header); + return this; + } + + private Response getResultValue(HttpResponse res) throws IOException { + return new SimpleResponse(res); + } + + private HttpResponse execute(HttpRequestBase request) throws IOException { + putHeader(request); + return httpClient.execute(request); + } + + private void putHeader(HttpUriRequest request) { + headers.forEach(request::setHeader); + } +} diff --git a/zlt-business/order-center/src/main/java/com/central/order/util/http/SimpleResponse.java b/zlt-business/order-center/src/main/java/com/central/order/util/http/SimpleResponse.java new file mode 100644 index 00000000..d66e16d3 --- /dev/null +++ b/zlt-business/order-center/src/main/java/com/central/order/util/http/SimpleResponse.java @@ -0,0 +1,26 @@ +package com.central.order.util.http; + +import org.apache.http.HttpResponse; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; + +/** + * @author wang + * @see + * @since 1.0 + */ +public class SimpleResponse implements Response { + + HttpResponse response; + + public SimpleResponse(HttpResponse response) { + this.response = response; + } + + + @Override + public byte[] asBytes() throws IOException { + return EntityUtils.toByteArray(response.getEntity()); + } +} diff --git a/zlt-business/order-center/src/main/resources/application.yml b/zlt-business/order-center/src/main/resources/application.yml new file mode 100644 index 00000000..c49b38f1 --- /dev/null +++ b/zlt-business/order-center/src/main/resources/application.yml @@ -0,0 +1,129 @@ +spring: + datasource: +# url: jdbc:mysql://${zlt.datasource.ip}:3306/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + url: jdbc:mysql://${zlt.datasource.ip}/order-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&allowMultiQueries=true + username: ${zlt.datasource.username} + password: ${zlt.datasource.password} + driver-class-name: com.mysql.cj.jdbc.Driver + +mybatis-plus: + mapper-locations: classpath:/mapper/*Mapper.xml + #实体扫描,多个package用逗号或者分号分隔 + typeAliasesPackage: com.central.device.model +# configuration: +# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + global-config: + db-config: + id-type: auto + +springdoc: + group-configs: + - group: 'default' + paths-to-match: '/**' + packages-to-scan: com.central.order.controller + +knife4j: + enable: true + setting: + swagger-model-name: 订单中心接口文档 +zlt: + #多租户配置 + tenant: + id: webApp + enable: false + ignoreTables: + - edit_task + - home_carousel + - sys_message + - wx_message_record + - wx_subscribe_status + - video_template + - profit_sharing + - order_statistics + ignoreSqls: + # 查询全部列表 +# - com.central.order.mapper.OrderMapper.findList + # 获取某个订单 +# - com.central.order.mapper.OrderMapper.getOrderByNumber + noIgnoreSqls: + - com.central.order.mapper.OrderMapper.findList + - com.central.order.mapper.TourismMapper.findList + - com.central.order.mapper.OrderFileMapper.findList + - com.central.order.mapper.QrCodeMapper.findList + - com.central.order.mapper.QrCodeMapper.save + # 微信支付商户号 +tencent: + merchantId: ${zlt.wxpay.merchantId} +# 微信支付商户密钥 + merchantSerialNumber: ${zlt.wxpay.merchantSerialNumber} +# 微信支付申请的应用ID + appId: ${zlt.wxpay.appId} +# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致) + notifyUrl: ${zlt.wxpay.notifyUrl} +# 微信支付API证书路径(如果需要证书的情况下,这里填写证书相关文件的路径) + privateKeyPath: ${zlt.wxpay.privateKeyPath} + apiV3Key: ${zlt.wxpay.apiV3Key} + appSecret: ${zlt.security.tencent.app-secret} + accessTokenUrl: ${zlt.security.tencent.accessTokenUrl} + getwxacodeUrl: https://api.weixin.qq.com/wxa/getwxacode?access_token= +# 微信退款通知地址 + refund-notify-url: ${zlt.wxrefund.notifyUrl} + notification: + app-id: + app-secret: + token: + encoding-aes-key: + pay: + profit-sharing: + enabled: true + max-retry-times: 3 + retry-interval: 300000 + platform-rate: 30 + timeout: 1800000 + async-enabled: true + async-pool-size: 5 + api: + profit-sharing-url: https://api.mch.weixin.qq.com/v3/profitsharing/orders + + +file: + oss-url: goflyapp.oss-cn-beijing.aliyuncs.com + cdn-url: cdn.goflytec.com + style: image/resize,m_mfit,w_300,h_250 + #审计日志 +# audit-log: +# enabled: true +# log-type: db +# datasource: +# driver-class-name: com.mysql.cj.jdbc.Driver +# jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai +# username: ${zlt.datasource.username} +# password: ${zlt.datasource.password} + +aliyun: + ims: + oss-endpoint: oss-cn-beijing.aliyuncs.com + access-key-id: LTAI5tSNV1RvexXpMMCZhxSe + access-key-secret: XocJRWU8emwjjvYLTrc04l91VZMkQK + endpoint: ice.cn-beijing.aliyuncs.com + region: cn-beijing + bucket: goflyapp # 使用实际存在的bucket名称 + +wx: + mp: + app-id: wx0ea85b13966d88e1 # 服务号应用id + secret: a90637566b2b73f41f8b1dabd64dc32b # 服务号应用密钥 + template-id: + payment-success: uscmjgLdw0cKBRq8vFyCOPbYj7p-fHuEOIhFwwIAe4A # 支付成功通知模板ID + video-complete: TEMPLATE_ID_2 # 视频完成通知模板ID + video-failure: TEMPLATE_ID_3 # 视频失败通知模板ID + + mini: + app-id: ${zlt.wxpay.appId} + secret: ${zlt.security.tencent.app-secret} + template: + pay-success: nSy7NGq1443YCfhgR81fgkeOVv9cSM5Ysp3nMoQYVpc + service-process: rgQCI3fMKPpgO-9nO3TzP-omohraGxX2suVioq7hQhk + activity-start: lgwkRnbdDc3mEwk3RMob43LpLHnLfglZtTkbFRPsPCA + order-complete: ZeIlAA6ImQLxBiLmo-53lM7wkL4KnuKKTGKWBZwYAdM + video-edit-complete: IXpL-Voztm3GM-zFj3sxA39qy8oRtAcxTiT7_Qsyz9Q diff --git a/zlt-business/order-center/src/main/resources/bootstrap.yml b/zlt-business/order-center/src/main/resources/bootstrap.yml new file mode 100644 index 00000000..1566517e --- /dev/null +++ b/zlt-business/order-center/src/main/resources/bootstrap.yml @@ -0,0 +1,15 @@ +server: + port: 7002 + +spring: + application: + name: order-center + cloud: + nacos: + discovery: + ip: 81.70.164.178 +# cloud: +# nacos: +# discovery: +# metadata: +# version: zlt diff --git a/zlt-business/order-center/src/main/resources/mapper/HomeCarouselMapper.xml b/zlt-business/order-center/src/main/resources/mapper/HomeCarouselMapper.xml new file mode 100644 index 00000000..953391f8 --- /dev/null +++ b/zlt-business/order-center/src/main/resources/mapper/HomeCarouselMapper.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/zlt-business/order-center/src/main/resources/mapper/MessageMapper.xml b/zlt-business/order-center/src/main/resources/mapper/MessageMapper.xml new file mode 100644 index 00000000..88aae0f7 --- /dev/null +++ b/zlt-business/order-center/src/main/resources/mapper/MessageMapper.xml @@ -0,0 +1,125 @@ + + + + + + id, title, content, type, status, create_time, read_time, + related_id, extra, user_id, tenant_id + + + + + + + + INSERT INTO sys_message ( + title, content, type, status, create_time, + related_id, extra, user_id, tenant_id + ) + VALUES + + ( + #{item.title}, + #{item.content}, + #{item.type}, + #{item.status}, + #{item.createTime}, + #{item.relatedId}, + #{item.extra}, + #{item.userId}, + #{item.tenantId} + ) + + + + + + UPDATE sys_message + SET status = #{status}, + read_time = #{readTime} + WHERE id IN + + #{id} + + AND user_id = #{userId} + + + + + + + + + + + DELETE FROM sys_message + WHERE status = 1 + AND read_time < #{beforeTime} + + AND user_id = #{userId} + + + AND tenant_id = #{tenantId} + + + + + + diff --git a/zlt-business/order-center/src/main/resources/mapper/OrderFileMapper.xml b/zlt-business/order-center/src/main/resources/mapper/OrderFileMapper.xml new file mode 100644 index 00000000..3c8e6b11 --- /dev/null +++ b/zlt-business/order-center/src/main/resources/mapper/OrderFileMapper.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + INSERT INTO order_files (user_id, order_no, file_id,tourism_id,file_path) + VALUES (#{userId}, #{order_no}, #{file_id}, #{tourism_id}, #{file_path}) + + + + + + + + + + diff --git a/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml b/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml new file mode 100644 index 00000000..ef813741 --- /dev/null +++ b/zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + INSERT INTO orders (user_id, order_amount, order_status) + VALUES (#{userId}, #{orderAmount}, #{orderStatus}) + + + + + + + + UPDATE orders + SET order_status = #{newStatus} + WHERE id = #{orderId} + + + + + + + + + + + diff --git a/zlt-business/order-center/src/main/resources/mapper/PaymentRecord.xml b/zlt-business/order-center/src/main/resources/mapper/PaymentRecord.xml new file mode 100644 index 00000000..63097516 --- /dev/null +++ b/zlt-business/order-center/src/main/resources/mapper/PaymentRecord.xml @@ -0,0 +1,20 @@ + + + + + + + + + INSERT INTO payment_records (order_id, payment_number, payment_amount, payment_time) + VALUES (#{orderId}, #{paymentNumber}, #{paymentAmount}, #{paymentTime}) + + + + + + diff --git a/zlt-business/order-center/src/main/resources/mapper/QrCodeMapper.xml b/zlt-business/order-center/src/main/resources/mapper/QrCodeMapper.xml new file mode 100644 index 00000000..da4c745b --- /dev/null +++ b/zlt-business/order-center/src/main/resources/mapper/QrCodeMapper.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + INSERT INTO qrcodes (code_id, tourism_id, device_sn) + VALUES (#{codeId}, #{tourismId}, #{deviceSn}) + + diff --git a/zlt-business/order-center/src/main/resources/mapper/RefundMapper.xml b/zlt-business/order-center/src/main/resources/mapper/RefundMapper.xml new file mode 100644 index 00000000..452ac2ab --- /dev/null +++ b/zlt-business/order-center/src/main/resources/mapper/RefundMapper.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/zlt-business/order-center/src/main/resources/mapper/TourismFileMapper.xml b/zlt-business/order-center/src/main/resources/mapper/TourismFileMapper.xml new file mode 100644 index 00000000..3ad7728f --- /dev/null +++ b/zlt-business/order-center/src/main/resources/mapper/TourismFileMapper.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/zlt-business/order-center/src/main/resources/mapper/TourismMapper.xml b/zlt-business/order-center/src/main/resources/mapper/TourismMapper.xml new file mode 100644 index 00000000..43ee01eb --- /dev/null +++ b/zlt-business/order-center/src/main/resources/mapper/TourismMapper.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + INSERT INTO tourisms (tourism_no, tourism_name, tourism_address,tourism_phone) + VALUES (#{tourismNo}, #{tourismName}, #{tourismAddress},#{tourismPhone}) + + diff --git a/zlt-business/pom.xml b/zlt-business/pom.xml index 6dfdc8c6..4ee19a6e 100644 --- a/zlt-business/pom.xml +++ b/zlt-business/pom.xml @@ -18,5 +18,9 @@ code-generator search-center + + device-center + + order-center - \ No newline at end of file + diff --git a/zlt-business/search-center/search-server/src/main/java/com/central/admin/service/impl/IndexServiceImpl.java b/zlt-business/search-center/search-server/src/main/java/com/central/admin/service/impl/IndexServiceImpl.java index a04ab78f..c26d95be 100644 --- a/zlt-business/search-center/search-server/src/main/java/com/central/admin/service/impl/IndexServiceImpl.java +++ b/zlt-business/search-center/search-server/src/main/java/com/central/admin/service/impl/IndexServiceImpl.java @@ -8,16 +8,16 @@ import com.central.common.utils.JsonUtil; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.util.EntityUtils; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.client.indices.CreateIndexRequest; -import org.elasticsearch.client.indices.CreateIndexResponse; -import org.elasticsearch.client.indices.GetIndexRequest; -import org.elasticsearch.client.indices.GetIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.Request; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.Response; +import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.client.indices.CreateIndexRequest; +import org.elasticsearch.client.indices.CreateIndexResponse; +import org.elasticsearch.client.indices.GetIndexRequest; +import org.elasticsearch.client.indices.GetIndexResponse; import org.elasticsearch.cluster.metadata.AliasMetadata; import org.elasticsearch.cluster.metadata.MappingMetadata; import org.elasticsearch.common.settings.Settings; @@ -25,7 +25,10 @@ import org.elasticsearch.common.xcontent.XContentType; import org.springframework.stereotype.Service; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * 索引 @@ -87,7 +90,7 @@ public class IndexServiceImpl implements IIndexService { TypeReference>> typeRef = new TypeReference>>() {}; listOfIndicesFromEs = mapper.readValue(rawBody, typeRef); } - return PageResult.>builder().data(listOfIndicesFromEs).code(0).build(); + return PageResult.>builder().data(listOfIndicesFromEs).resp_code(0).build(); } @Override diff --git a/zlt-business/user-center/pom.xml b/zlt-business/user-center/pom.xml index 70d6aa41..454e0497 100644 --- a/zlt-business/user-center/pom.xml +++ b/zlt-business/user-center/pom.xml @@ -79,6 +79,14 @@ org.hibernate hibernate-validator
+ + + + com.zlt + zlt-wechat-common-core + ${project.version} + + @@ -122,4 +130,4 @@ ${project.artifactId} - \ No newline at end of file + diff --git a/zlt-business/user-center/src/main/java/com/central/UserCenterApp.java b/zlt-business/user-center/src/main/java/com/central/UserCenterApp.java index 5da788be..540936ed 100644 --- a/zlt-business/user-center/src/main/java/com/central/UserCenterApp.java +++ b/zlt-business/user-center/src/main/java/com/central/UserCenterApp.java @@ -2,8 +2,10 @@ package com.central; import com.central.common.lb.annotation.EnableFeignInterceptor; import com.central.search.annotation.EnableSearchClient; +import com.central.user.properties.TencentProperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.transaction.annotation.EnableTransactionManagement; @@ -15,6 +17,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @EnableFeignInterceptor @SpringBootApplication +@EnableConfigurationProperties(TencentProperties.class) public class UserCenterApp { public static void main(String[] args) { SpringApplication.run(UserCenterApp.class, args); diff --git a/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java index 3ad3081e..bbc7a930 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java +++ b/zlt-business/user-center/src/main/java/com/central/user/controller/SysMenuController.java @@ -1,13 +1,14 @@ package com.central.user.controller; -import java.util.*; -import java.util.stream.Collectors; - import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ObjectUtil; import com.central.common.constant.CommonConstant; import com.central.common.context.LoginUserContextHolder; -import com.central.common.model.*; +import com.central.common.model.LoginAppUser; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.model.SysMenu; +import com.central.user.service.ISysMenuService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; @@ -16,7 +17,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.*; -import com.central.user.service.ISysMenuService; +import java.util.*; +import java.util.stream.Collectors; /** * @author 作者 owen E-mail: 624191343@qq.com @@ -125,14 +127,14 @@ public class SysMenuController { @GetMapping("/findAlls") public PageResult findAlls() { List list = menuService.findAll(); - return PageResult.builder().data(list).code(0).count((long) list.size()).build(); + return PageResult.builder().data(list).resp_code(0).count((long) list.size()).build(); } @Operation(summary = "获取菜单以及顶级菜单") @GetMapping("/findOnes") public PageResult findOnes() { List list = menuService.findOnes(); - return PageResult.builder().data(list).code(0).count((long) list.size()).build(); + return PageResult.builder().data(list).resp_code(0).count((long) list.size()).build(); } /** diff --git a/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java index 1cf9759a..2fee7d17 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java +++ b/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java @@ -1,11 +1,5 @@ package com.central.user.controller; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.util.ObjectUtil; import com.central.common.constant.CommonConstant; @@ -17,25 +11,35 @@ import com.central.search.client.service.IQueryService; import com.central.search.model.LogicDelDto; import com.central.search.model.SearchDto; import com.central.user.model.SysUserExcel; +import com.central.user.properties.TencentProperties; +import com.central.user.service.ISysUserService; +import com.central.user.service.MiniAppConfigService; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; - -import com.central.user.service.ISysUserService; - -import lombok.extern.slf4j.Slf4j; +import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; -import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.*; /** * @author 作者 owen E-mail: 624191343@qq.com @@ -58,6 +62,12 @@ public class SysUserController { @Autowired private IQueryService queryService; + @Autowired + private TencentProperties tencentProperties; + + @Autowired + private MiniAppConfigService miniAppConfigService; + /** * 当前登录用户 LoginAppUser * @@ -110,6 +120,19 @@ public class SysUserController { return appUserService.findByOpenId(openId); } + /** + * 根据WxOpenId查询用户信息 + * + * @param openId openId + */ + @GetMapping(value = "/users-anon/wxOpenId") + @Operation(summary = "根据WxOpenId查询用户") + public SysUser findByWxOpenId(@RequestParam("openId") String openId, + @RequestParam(required = false) String mobile, + @RequestParam(required = false) String unionId) throws Exception { + return appUserService.findByWxOpenid(openId,mobile,unionId); + } + @GetMapping("/users/{id}") public SysUser findUserById(@PathVariable Long id) { return appUserService.getById(id); @@ -127,6 +150,12 @@ public class SysUserController { appUserService.updateById(sysUser); } + @PatchMapping("/user") + @CachePut(value = "user", key = "#sysUser.username", unless="#result == null") + public Result updateSysUserInfo(@RequestBody SysUser sysUser) { + return Result.succeed(appUserService.updateById(sysUser),"更新成功"); + } + /** * 管理后台给用户分配角色 * @@ -304,10 +333,138 @@ public class SysUserController { return sysUser; } + /** + * APP更新用户手机号 + * @param code + */ + @PutMapping("/code/mobile") + @CachePut(value = "user", key = "#sysUser.username", unless="#result == null") + @AuditLog(operation = "'更新用户:' + #sysUser") + public void updateSysUserMobile(@RequestParam String code) { + SysUser sysUser = getLoginAppUser().getData(); + sysUser.setMobile(getUserPhoneNumber(code)); + appUserService.updateById(sysUser); + } + + /** + * 获取小程序配置 + * + * @param + * @return + */ + @GetMapping("/users-anon/miniApp") + public MiniAppConfig findAppByAppId(@RequestParam String appCode) { + return miniAppConfigService.getByAppCode(appCode); + } + /** * 是否超级管理员 */ private boolean checkAdmin(long id) { return id == 1L; } + + /** + * 获取微信访问token + * @return access_token + */ + private String getTencentAccessToken(){ + + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap params = new LinkedMultiValueMap<>(); + params.add("appid", tencentProperties.getAppId()); + params.add("secret", tencentProperties.getAppSecret()); + params.add("grant_type", "client_credential"); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED); + + HttpEntity> requestEntity = new HttpEntity<>(params, headers); + + ResponseEntity responseEntity = restTemplate + .exchange(tencentProperties.getGetPhonenumberUrl()+"?grant_type=client_credential&appid=" + tencentProperties.getAppId()+"&secret=" + tencentProperties.getAppSecret(), + HttpMethod.GET, + requestEntity, + String.class); + + if (responseEntity.getStatusCode().is2xxSuccessful() ) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + return objectMapper.readValue(responseEntity.getBody(), Map.class).get("access_token").toString(); + } catch (Exception e) { + throw new EmptyStackException(); + } + }else { + throw new EmptyStackException(); + } + } + + /** + * 获取微信用户手机号 + * @return access_token + */ + private String getUserPhoneNumber(String code){ + + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap params = new LinkedMultiValueMap<>(); + + params.add("code", code); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED); + + HttpEntity> requestEntity = new HttpEntity<>(params, headers); + + ResponseEntity responseEntity = restTemplate + .exchange("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getTencentAccessToken(), + HttpMethod.POST, + requestEntity, + String.class); + + if (responseEntity.getStatusCode().is2xxSuccessful() ) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + return objectMapper.readValue(responseEntity.getBody(), Map.class).get("phone_info").toString(); + } catch (Exception e) { + throw new EmptyStackException(); + } + }else { + throw new EmptyStackException(); + } + } + + /** + * 新增或修改小程序配置 + */ + @PostMapping("/miniApp/saveOrUpdate") + @Operation(summary = "新增或修改小程序配置") + public Result saveOrUpdateMiniAppConfig(@RequestBody MiniAppConfig config) { + if (ObjectUtil.isNull(config.getAppCode())) { + String codeId = UUID.randomUUID().toString(); + config.setAppCode(codeId); + } + boolean success = miniAppConfigService.saveOrUpdate(config); + return success ? Result.succeed(true, "操作成功") : Result.failed("操作失败"); + } + + @Operation(summary = "小程序配置分页查询") + @Parameters({ + @Parameter(name = "page", description = "分页起始位置", required = true, in = ParameterIn.QUERY), + @Parameter(name = "limit", description = "分页结束位置", required = true, in = ParameterIn.QUERY) + }) + @GetMapping("/miniApp/list") + public PageResult findMiniAppConfigs(@RequestParam Map params) { + return miniAppConfigService.findMiniAppConfigs(params); + } + + /** + * 根据ID查询小程序配置 + */ + @GetMapping("/miniApp/{id}") + @Operation(summary = "根据ID查询小程序配置") + public Result getMiniAppConfigById(@PathVariable Long id) { + MiniAppConfig config = miniAppConfigService.getById(id); + return config != null ? Result.succeed(config) : Result.failed("未找到配置"); + } + } diff --git a/zlt-business/user-center/src/main/java/com/central/user/controller/SysWechatConfigController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysWechatConfigController.java new file mode 100644 index 00000000..b0b534cd --- /dev/null +++ b/zlt-business/user-center/src/main/java/com/central/user/controller/SysWechatConfigController.java @@ -0,0 +1,107 @@ +package com.central.user.controller; + +import com.central.common.context.TenantContextHolder; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.user.service.WechatConfigService; +import com.central.wechat.entity.WechatConfig; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.util.Map; + +@Slf4j +@RestController +@RequiredArgsConstructor +@Tag(name = "微信配置管理") +@RequestMapping("/wechat/config") +public class SysWechatConfigController { + + @Resource + private WechatConfigService wechatConfigService; + + + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in= ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return wechatConfigService.findList(params); + } + + @Operation(summary = "获取微信配置") + @GetMapping("/{type}") + public WechatConfig getConfig(@PathVariable String type) { + return wechatConfigService.getConfig(type, TenantContextHolder.getTenant()); + } + + @Operation(summary = "获取微信配置") + @GetMapping("/app/{id}") + public WechatConfig getConfigByAppId(@PathVariable("id") String appId) { + return wechatConfigService.getConfig(appId); + } + + @GetMapping(value = "/serial/{serialNumber}") + WechatConfig getConfigBySerialNumber(@PathVariable("serialNumber") String serialNumber) { + + return wechatConfigService.getConfigBySerialNumber(serialNumber); + } + + @Operation(summary = "保存微信配置") + @PostMapping + public Result saveConfig(@RequestBody WechatConfig config) { + if (config.getId() == null) { + config.setTenantId(TenantContextHolder.getTenant()); + } + return Result.succeed(wechatConfigService.saveConfig(config)); + } + + @Operation(summary = "更新微信配置") + @PutMapping + public Result updateConfig(@RequestBody WechatConfig config) { + return Result.succeed(wechatConfigService.updateConfig(config)); + } + + @Operation(summary = "删除微信配置") + @DeleteMapping("/{id}") + public Result deleteConfig(@PathVariable Long id) { + return Result.succeed(wechatConfigService.deleteConfig(id)); + } + + @Operation(summary = "上传支付私钥") + @PostMapping("/private-key") + public Result uploadPrivateKey(@RequestParam("file") MultipartFile file) { + try { + String privateKey = new String(file.getBytes()); + WechatConfig wechatConfig = wechatConfigService.getConfig("PAY",TenantContextHolder.getTenant()); + wechatConfig.setPrivateKey(privateKey); + return Result.succeed(wechatConfigService.updateConfig(wechatConfig)); + } catch (Exception e) { + log.error("上传私钥文件失败", e); + return Result.failed("上传私钥文件失败"); + } + } + + @Operation(summary = "切换微信配置") + @PostMapping("/switch/{type}") + public Result switchConfig(@PathVariable String type) { + return Result.succeed(wechatConfigService.switchConfig(type, TenantContextHolder.getTenant())); + } + + @Operation(summary = "获取当前配置") + @GetMapping("/current/{type}") + public Result getCurrentConfig(@PathVariable String type) { + return Result.succeed(wechatConfigService.getConfig(type, TenantContextHolder.getTenant())); + } + +} diff --git a/zlt-business/user-center/src/main/java/com/central/user/mapper/MiniAppConfigMapper.java b/zlt-business/user-center/src/main/java/com/central/user/mapper/MiniAppConfigMapper.java new file mode 100644 index 00000000..a2bbd402 --- /dev/null +++ b/zlt-business/user-center/src/main/java/com/central/user/mapper/MiniAppConfigMapper.java @@ -0,0 +1,12 @@ +package com.central.user.mapper; + +import com.central.common.model.MiniAppConfig; +import com.central.db.mapper.SuperMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; + +@Mapper +public interface MiniAppConfigMapper extends SuperMapper { + @Select("SELECT * FROM mini_app_config WHERE appCode = #{appCode} AND status = 1 LIMIT 1") + MiniAppConfig selectByAppCode(String appCode); +} diff --git a/zlt-business/user-center/src/main/java/com/central/user/mapper/WechatConfigMapper.java b/zlt-business/user-center/src/main/java/com/central/user/mapper/WechatConfigMapper.java new file mode 100644 index 00000000..46bcf64f --- /dev/null +++ b/zlt-business/user-center/src/main/java/com/central/user/mapper/WechatConfigMapper.java @@ -0,0 +1,35 @@ +package com.central.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.wechat.entity.WechatConfig; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface WechatConfigMapper extends BaseMapper { + + @Select("") + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/user-center/src/main/java/com/central/user/model/SysWechatConfig.java b/zlt-business/user-center/src/main/java/com/central/user/model/SysWechatConfig.java new file mode 100644 index 00000000..d3ea78d8 --- /dev/null +++ b/zlt-business/user-center/src/main/java/com/central/user/model/SysWechatConfig.java @@ -0,0 +1,114 @@ +package com.central.user.model; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +@Data +@TableName("sys_wechat_config") +public class SysWechatConfig { + + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 租户ID + */ + private String tenantId; + + /** + * 配置类型:MP-公众号,MINI-小程序,PAY-支付 + */ + private String type; + + /** + * 商户ID + */ + private String merchantId; + + /** + * 应用ID + */ + private String appId; + + /** + * 应用密钥 + */ + private String appSecret; + + /** + * 商户API密钥 + */ + private String mchKey; + + /** + * 商户证书序列号 + */ + private String mchSerialNo; + + /** + * 商户私钥文件路径 + */ + private String privateKeyPath; + + /** + * APIv3密钥 + */ + private String apiV3Key; + + /** + * 支付回调地址 + */ + private String notifyUrl; + + /** + * 微信公众号token + */ + private String token; + + /** + * 微信公众号aesKey + */ + private String aesKey; + + /** + * 支付成功通知模板ID + */ + private String paymentSuccessTemplateId; + + /** + * 视频处理完成通知模板ID + */ + private String videoCompleteTemplateId; + + /** + * 视频处理失败通知模板ID + */ + private String videoFailTemplateId; + + /** + * 是否启用分账 + */ + private Boolean profitSharingEnabled; + + /** + * 是否启用异步处理 + */ + private Boolean asyncEnabled; + + /** + * 异步处理线程池大小 + */ + private Integer asyncPoolSize; + + /** + * 状态:0-禁用,1-启用 + */ + private Integer status; + + /** + * 备注 + */ + private String remark; +} \ No newline at end of file diff --git a/zlt-business/user-center/src/main/java/com/central/user/properties/TencentProperties.java b/zlt-business/user-center/src/main/java/com/central/user/properties/TencentProperties.java new file mode 100644 index 00000000..a820f9d8 --- /dev/null +++ b/zlt-business/user-center/src/main/java/com/central/user/properties/TencentProperties.java @@ -0,0 +1,26 @@ +package com.central.user.properties; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; + +/** + * 腾讯认证配置 + * + * @author lsl + * @version 1.0 + * @date 2024/12/20 + *

+ * + */ +@Setter +@Getter +@ConfigurationProperties(prefix = "zlt.tencent") +@RefreshScope +public class TencentProperties { + private String appId; + private String appSecret; + private String accessTokenUrl; + private String getPhonenumberUrl; +} diff --git a/zlt-business/user-center/src/main/java/com/central/user/service/ISysUserService.java b/zlt-business/user-center/src/main/java/com/central/user/service/ISysUserService.java index bd1a301e..75c2031f 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/service/ISysUserService.java +++ b/zlt-business/user-center/src/main/java/com/central/user/service/ISysUserService.java @@ -1,15 +1,15 @@ package com.central.user.service; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.central.common.service.ISuperService; -import com.central.user.model.SysUserExcel; import com.central.common.model.PageResult; import com.central.common.model.Result; import com.central.common.model.SysRole; import com.central.common.model.SysUser; +import com.central.common.service.ISuperService; +import com.central.user.model.SysUserExcel; + +import java.util.List; +import java.util.Map; +import java.util.Set; /** * @author zlt @@ -29,6 +29,8 @@ public interface ISysUserService extends ISuperService { SysUser findByMobile(String username); + SysUser findByWxOpenid(String wxOpenid,String mobile,String unionId) throws Exception; + /** * 通过SysUser 把roles和permissions也查询出来 * @param sysUser @@ -55,6 +57,7 @@ public interface ISysUserService extends ISuperService { */ SysUser selectByOpenId(String openId); + /** * 用户分配角色 * @param id diff --git a/zlt-business/user-center/src/main/java/com/central/user/service/MiniAppConfigService.java b/zlt-business/user-center/src/main/java/com/central/user/service/MiniAppConfigService.java new file mode 100644 index 00000000..a06ec2a3 --- /dev/null +++ b/zlt-business/user-center/src/main/java/com/central/user/service/MiniAppConfigService.java @@ -0,0 +1,13 @@ +package com.central.user.service; + +import com.central.common.model.MiniAppConfig; +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; + +import java.util.Map; + +public interface MiniAppConfigService extends ISuperService { + MiniAppConfig getByAppCode(String appCode); + + PageResult findMiniAppConfigs(Map params); +} diff --git a/zlt-business/user-center/src/main/java/com/central/user/service/WechatConfigService.java b/zlt-business/user-center/src/main/java/com/central/user/service/WechatConfigService.java new file mode 100644 index 00000000..7e203e9b --- /dev/null +++ b/zlt-business/user-center/src/main/java/com/central/user/service/WechatConfigService.java @@ -0,0 +1,75 @@ +package com.central.user.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.central.common.model.PageResult; +import com.central.wechat.entity.WechatConfig; + +import java.util.Map; + +public interface WechatConfigService extends IService { + + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 获取微信配置 + * + * @param type 配置类型 + * @param tenantId 商户ID + * @return 微信配置 + */ + WechatConfig getConfig(String type, String tenantId); + + /** + * 获取微信配置 + * + * @param appId 商户ID + * @return 微信配置 + */ + WechatConfig getConfig(String appId); + + /** + * 获取微信配置 + * + * @param serialNumber 商户序列号 + * @return 微信配置 + */ + WechatConfig getConfigBySerialNumber(String serialNumber); + + /** + * 保存微信配置 + * + * @param config 微信配置 + * @return 是否成功 + */ + boolean saveConfig(WechatConfig config); + + /** + * 更新微信配置 + * + * @param config 微信配置 + * @return 是否成功 + */ + boolean updateConfig(WechatConfig config); + + /** + * 删除微信配置 + * + * @param id 配置ID + * @return 是否成功 + */ + boolean deleteConfig(Long id); + + /** + * 切换当前使用的微信配置 + * + * @param type 配置类型 + * @param merchantId 商户ID + * @return 是否成功 + */ + boolean switchConfig(String type, String merchantId); +} diff --git a/zlt-business/user-center/src/main/java/com/central/user/service/impl/MiniAppConfigServiceImpl.java b/zlt-business/user-center/src/main/java/com/central/user/service/impl/MiniAppConfigServiceImpl.java new file mode 100644 index 00000000..7a2d9487 --- /dev/null +++ b/zlt-business/user-center/src/main/java/com/central/user/service/impl/MiniAppConfigServiceImpl.java @@ -0,0 +1,44 @@ +package com.central.user.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.MiniAppConfig; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.user.mapper.MiniAppConfigMapper; +import com.central.user.service.MiniAppConfigService; +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +@Service +public class MiniAppConfigServiceImpl extends SuperServiceImpl implements MiniAppConfigService { + + @Autowired + private MiniAppConfigMapper miniAppConfigMapper; + + @Override + public MiniAppConfig getByAppCode(String appCode) { + return miniAppConfigMapper.selectByAppCode(appCode); + } + + @Override + public PageResult findMiniAppConfigs(Map params) { + // 解析分页参数 + int pageNum = MapUtils.getInteger(params, "page"); + int pageSize = MapUtils.getInteger(params, "limit"); + Page page = new Page<>(pageNum, pageSize); + + // 如果有自定义的 findList,可用,否则用 MyBatis-Plus 的 selectPage + List list = baseMapper.selectPage(page, null).getRecords(); + long total = page.getTotal(); + + return PageResult.builder() + .data(list) + .resp_code(0) + .count(total) + .build(); + } +} diff --git a/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysRoleServiceImpl.java b/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysRoleServiceImpl.java index 45644d54..3f1d7592 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysRoleServiceImpl.java +++ b/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysRoleServiceImpl.java @@ -1,28 +1,26 @@ package com.central.user.service.impl; -import java.util.List; -import java.util.Map; - import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.constant.CommonConstant; import com.central.common.context.LoginUserContextHolder; import com.central.common.lock.DistributedLock; -import com.central.common.model.*; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.model.SysRole; import com.central.common.service.impl.SuperServiceImpl; +import com.central.user.mapper.SysRoleMapper; +import com.central.user.mapper.SysRoleMenuMapper; +import com.central.user.mapper.SysUserRoleMapper; +import com.central.user.service.ISysRoleService; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import com.central.user.mapper.SysRoleMapper; -import com.central.user.mapper.SysRoleMenuMapper; -import com.central.user.mapper.SysUserRoleMapper; -import com.central.user.service.ISysRoleService; - -import lombok.extern.slf4j.Slf4j; - import javax.annotation.Resource; +import java.util.List; +import java.util.Map; /** * @author 作者 owen E-mail: 624191343@qq.com @@ -63,7 +61,7 @@ public class SysRoleServiceImpl extends SuperServiceImpl Integer limit = MapUtils.getInteger(params, "limit"); Page page = new Page<>(curPage == null ? 0 : curPage, limit == null ? -1 : limit); List list = baseMapper.findList(page, params); - return PageResult.builder().data(list).code(0).count(page.getTotal()).build(); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); } @Override diff --git a/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java b/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java index 47cfa233..d1357726 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java +++ b/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java @@ -1,8 +1,5 @@ package com.central.user.service.impl; -import java.util.*; -import java.util.stream.Collectors; - import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @@ -12,10 +9,12 @@ import com.central.common.lock.DistributedLock; import com.central.common.model.*; import com.central.common.service.impl.SuperServiceImpl; import com.central.user.mapper.SysRoleMenuMapper; +import com.central.user.mapper.SysUserMapper; import com.central.user.model.SysRoleUser; import com.central.user.model.SysUserExcel; -import com.central.user.mapper.SysUserMapper; import com.central.user.service.ISysRoleUserService; +import com.central.user.service.ISysUserService; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; @@ -26,11 +25,9 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; -import com.central.user.service.ISysUserService; - -import lombok.extern.slf4j.Slf4j; - import javax.annotation.Resource; +import java.util.*; +import java.util.stream.Collectors; /** * @author 作者 owen E-mail: 624191343@qq.com @@ -60,8 +57,8 @@ public class SysUserServiceImpl extends SuperServiceImpl } @Override - public SysUser findByOpenId(String username) { - SysUser sysUser = this.selectByOpenId(username); + public SysUser findByOpenId(String openId) { + SysUser sysUser = this.selectByOpenId(openId); setUserPermission(sysUser); return sysUser; } @@ -73,6 +70,41 @@ public class SysUserServiceImpl extends SuperServiceImpl return sysUser; } + @Override + public SysUser findByWxOpenid(String wxOpenid, String mobile, String unionId) throws Exception { + log.info("开发平台unionId:unionId:{}", unionId); + SysUser sysUser = this.selectByOpenId(wxOpenid); + + // 如果用户存在,更新 unionId(无论是否为空都更新) + if (ObjectUtils.isNotEmpty(sysUser)) { + if (StringUtils.isNotEmpty(unionId)) { + sysUser.setUnionId(unionId); + log.info("更新用户unionId: {}", unionId); + } + if (StringUtils.isNotEmpty(mobile)) { + sysUser.setMobile(mobile); + } + } else { + // 创建新用户 + sysUser = new SysUser(); + sysUser.setOpenId(wxOpenid); + sysUser.setUsername(wxOpenid); + sysUser.setType(UserType.APP.name()); + sysUser.setPassword(wxOpenid); + sysUser.setEnabled(Boolean.TRUE); + sysUser.setMobile(mobile); + sysUser.setUnionId(unionId); + } + + String username = sysUser.getUsername(); + boolean result = super.saveOrUpdateIdempotency(sysUser, lock, + LOCK_KEY_USERNAME + username, + new QueryWrapper().eq("username", username), + username + "已存在"); + + return result ? sysUser : new SysUser(); + } + @Override public void setUserPermission(SysUser sysUser) { if (sysUser != null) { @@ -189,7 +221,7 @@ public class SysUserServiceImpl extends SuperServiceImpl list.forEach(u -> u.setRoles(sysRoles.stream().filter(r -> !ObjectUtils.notEqual(u.getId(), r.getUserId())) .collect(Collectors.toList()))); } - return PageResult.builder().data(list).code(0).count(total).build(); + return PageResult.builder().data(list).resp_code(0).count(total).build(); } @Override @@ -262,4 +294,4 @@ public class SysUserServiceImpl extends SuperServiceImpl } return sysUserExcels; } -} \ No newline at end of file +} diff --git a/zlt-business/user-center/src/main/java/com/central/user/service/impl/WechatConfigServiceImpl.java b/zlt-business/user-center/src/main/java/com/central/user/service/impl/WechatConfigServiceImpl.java new file mode 100644 index 00000000..dad520dd --- /dev/null +++ b/zlt-business/user-center/src/main/java/com/central/user/service/impl/WechatConfigServiceImpl.java @@ -0,0 +1,79 @@ +package com.central.user.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.central.common.model.PageResult; +import com.central.user.mapper.WechatConfigMapper; +import com.central.user.service.WechatConfigService; +import com.central.wechat.entity.WechatConfig; +import lombok.RequiredArgsConstructor; +import org.apache.commons.collections4.MapUtils; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +@RequiredArgsConstructor +@Service +public class WechatConfigServiceImpl extends ServiceImpl implements WechatConfigService { + + private static final String CACHE_NAME = "wechat:config"; + private static final String CACHE_KEY_PATTERN = "#type + ':' + #tenantId"; + + @Override + public PageResult findList(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page", 1), MapUtils.getInteger(params, "limit", 10)); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override +// @Cacheable(value = CACHE_NAME, key = CACHE_KEY_PATTERN, unless = "#result == null") + public WechatConfig getConfig(String type, String tenantId) { + return getOne(new LambdaQueryWrapper() + .eq(WechatConfig::getType, type) + .eq(WechatConfig::getTenantId, tenantId) + .eq(WechatConfig::getStatus, 1)); + } + + @Override + public WechatConfig getConfig(String appId) { + return getOne(new LambdaQueryWrapper() + .eq(WechatConfig::getAppId, appId) + .eq(WechatConfig::getStatus, 1)); + } + + @Override + public WechatConfig getConfigBySerialNumber(String serialNumber) { + return getOne(new LambdaQueryWrapper() + .eq(WechatConfig::getMchSerialNo, serialNumber) + .eq(WechatConfig::getStatus, 1)); + } + + @Override + @CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN) + public boolean saveConfig(WechatConfig config) { + return save(config); + } + + @Override + @CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN) + public boolean updateConfig(WechatConfig config) { + return updateById(config); + } + + @Override + @CacheEvict(value = CACHE_NAME, allEntries = true) + public boolean deleteConfig(Long id) { + return removeById(id); + } + + @Override + @CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN) + public boolean switchConfig(String type, String tenantId) { + // 这里可以添加切换配置的具体逻辑 + return true; + } +} diff --git a/zlt-business/user-center/src/main/resources/application.yml b/zlt-business/user-center/src/main/resources/application.yml index b9a3fa78..def23f46 100644 --- a/zlt-business/user-center/src/main/resources/application.yml +++ b/zlt-business/user-center/src/main/resources/application.yml @@ -1,6 +1,7 @@ spring: datasource: - url: jdbc:mysql://${zlt.datasource.ip}:3306/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai +# url: jdbc:mysql://${zlt.datasource.ip}:3306/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + url: jdbc:mysql://${zlt.datasource.ip}/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: ${zlt.datasource.username} password: ${zlt.datasource.password} driver-class-name: com.mysql.cj.jdbc.Driver @@ -38,6 +39,7 @@ zlt: - sys_user - sys_role_user - sys_role_menu + - mini_app_config ignoreSqls: # 用户关联角色时,显示所有角色 - com.central.user.mapper.SysRoleMapper.findAll @@ -56,7 +58,13 @@ zlt: - com.central.user.mapper.SysRoleMapper.findList # 菜单列表 - com.central.user.mapper.SysMenuMapper.selectList - #审计日志 + + tencent: + app-id: ${zlt.security.tencent.app-id} + app-secret: ${zlt.security.tencent.app-secret} + access-token-url: https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token= + get-phonenumber-url: https://api.weixin.qq.com/cgi-bin/token +#审计日志 # audit-log: # enabled: true # log-type: db @@ -64,4 +72,4 @@ zlt: # driver-class-name: com.mysql.cj.jdbc.Driver # jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai # username: ${zlt.datasource.username} -# password: ${zlt.datasource.password} \ No newline at end of file +# password: ${zlt.datasource.password} diff --git a/zlt-business/user-center/src/main/resources/bootstrap.yml b/zlt-business/user-center/src/main/resources/bootstrap.yml index 37d61a52..a23d0891 100644 --- a/zlt-business/user-center/src/main/resources/bootstrap.yml +++ b/zlt-business/user-center/src/main/resources/bootstrap.yml @@ -4,8 +4,12 @@ server: spring: application: name: user-center + cloud: + nacos: + discovery: + ip: 124.222.128.40 # cloud: # nacos: # discovery: # metadata: -# version: zlt \ No newline at end of file +# version: zlt diff --git a/zlt-commons/pom.xml b/zlt-commons/pom.xml index 41e58f17..fa2d2adf 100644 --- a/zlt-commons/pom.xml +++ b/zlt-commons/pom.xml @@ -22,5 +22,7 @@ zlt-elasticsearch-spring-boot-starter zlt-oss-spring-boot-starter zlt-zookeeper-spring-boot-starter + zlt-wechat-common-core + zlt-wechat-spring-boot-starter - \ No newline at end of file + diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/SecurityProperties.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/SecurityProperties.java index 7947eaf9..ddeec661 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/SecurityProperties.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/SecurityProperties.java @@ -25,4 +25,6 @@ public class SecurityProperties { private ValidateCodeProperties code = new ValidateCodeProperties(); private ResourceServerProperties resourceServer = new ResourceServerProperties(); + + private TencentProperties tencent = new TencentProperties(); } diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/TencentProperties.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/TencentProperties.java new file mode 100644 index 00000000..a35b6d01 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/TencentProperties.java @@ -0,0 +1,23 @@ +package com.central.oauth2.common.properties; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; + +/** + * 腾讯认证配置 + * + * @author lsl + * @version 1.0 + * @date 2024/12/20 + *

+ * + */ +@Setter +@Getter +public class TencentProperties { + private String appId; + private String appSecret; + private String jscode2sessionUrl; +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TencentAuthenticationToken.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TencentAuthenticationToken.java new file mode 100644 index 00000000..57d2a661 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TencentAuthenticationToken.java @@ -0,0 +1,41 @@ +package com.central.oauth2.common.token; + +import lombok.Getter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.oauth2.core.AuthorizationGrantType; + +import java.util.Collection; + +/** + * @author: lsl + * @date: 2024/12/16 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Getter +public class TencentAuthenticationToken extends BaseAuthenticationToken { + public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("tencent"); + private final Object principal; + private final String encryptedData; + private final String iv; + private final String appCode; + + public TencentAuthenticationToken(String code, String encryptedData, String iv, String appCode) { + super(GRANT_TYPE); + this.principal = code; + this.encryptedData = encryptedData; + this.iv = iv; + this.appCode = appCode; + super.setAuthenticated(true); + } + + public TencentAuthenticationToken(UserDetails user, Collection authorities, String encryptedData, String iv, String appCode) { + super(authorities); + this.principal = user; + this.encryptedData = encryptedData; + this.iv = iv; + this.appCode = appCode; + } +} diff --git a/zlt-commons/zlt-common-core/pom.xml b/zlt-commons/zlt-common-core/pom.xml index 959f9d92..950294e0 100644 --- a/zlt-commons/zlt-common-core/pom.xml +++ b/zlt-commons/zlt-common-core/pom.xml @@ -102,5 +102,20 @@ org.springframework spring-webmvc + + commons-lang + commons-lang + 2.6 + compile + + + javax.servlet + javax.servlet-api + true + + + org.springframework + spring-test + - \ No newline at end of file + diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/CommonConstant.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/CommonConstant.java index f7004656..211d46fe 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/CommonConstant.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/CommonConstant.java @@ -94,6 +94,7 @@ public interface CommonConstant { */ String MONTH_FORMAT = "yyyy-MM"; String DATE_FORMAT = "yyyy-MM-dd"; + String DATEMINUTE_FORMAT = "yyyy-MM-dd HH:mm"; String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; String SIMPLE_MONTH_FORMAT = "yyyyMM"; String SIMPLE_DATE_FORMAT = "yyyyMMdd"; diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/ServiceNameConstants.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/ServiceNameConstants.java index ce6ace1a..4ce7a657 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/ServiceNameConstants.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/ServiceNameConstants.java @@ -16,4 +16,12 @@ public interface ServiceNameConstants { * 搜索中心服务 */ String SEARCH_SERVICE = "search-center"; + + String UAA_SERVICE = "uaa-center"; + + String DEVICE_SERVICE = "device-center"; + + String FILE_SERVICE = "file-center"; + + String ORDER_SERVICE = "order-center"; } diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java index fbef509d..155b5d89 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java @@ -2,6 +2,7 @@ package com.central.common.feign; import com.central.common.constant.ServiceNameConstants; import com.central.common.feign.fallback.UserServiceFallbackFactory; +import com.central.common.model.MiniAppConfig; import com.central.common.model.SysRole; import com.central.common.model.SysUser; import org.springframework.cloud.openfeign.FeignClient; @@ -51,6 +52,14 @@ public interface UserService { @GetMapping(value = "/users-anon/openId", params = "openId") SysUser findByOpenId(@RequestParam("openId") String openId); + /** + * 根据OpenId查询用户信息 + * + * @param openId openId + */ + @GetMapping(value = "/users-anon/wxOpenId", params = {"openId","mobile"}) + SysUser findByWxOpenId(@RequestParam("openId") String openId, @RequestParam("mobile") String mobile,@RequestParam("unionId") String unionId); + /** * 获取带角色的用户信息 @@ -58,7 +67,7 @@ public interface UserService { * @return */ @GetMapping(value = "/users/roleUser/{username}") - public SysUser selectRoleUser(@PathVariable("username") String username); + SysUser selectRoleUser(@PathVariable("username") String username); /** * 获取用户的角色 @@ -67,5 +76,9 @@ public interface UserService { * @return */ @GetMapping("/users/{id}/roles") - public List findRolesByUserId(@PathVariable("id") Long id); + List findRolesByUserId(@PathVariable("id") Long id); + + + @GetMapping("/users-anon/miniApp") + MiniAppConfig getByAppid(@RequestParam("appCode") String appCode); } diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java index eb83c655..58028521 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java @@ -1,10 +1,11 @@ package com.central.common.feign.fallback; import com.central.common.feign.UserService; +import com.central.common.model.MiniAppConfig; import com.central.common.model.SysRole; import com.central.common.model.SysUser; -import org.springframework.cloud.openfeign.FallbackFactory; import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; import java.util.Collections; import java.util.List; @@ -44,6 +45,12 @@ public class UserServiceFallbackFactory implements FallbackFactory return new SysUser(); } + @Override + public SysUser findByWxOpenId(String openId,String mobile,String unionId) { + log.error("通过wxOpenId查询用户异常:{}", openId, throwable); + return new SysUser(); + } + /** * 获取带角色的用户信息 * @@ -66,6 +73,11 @@ public class UserServiceFallbackFactory implements FallbackFactory log.error("通过用户id查询角色列表异常:{}", id, throwable); return Collections.emptyList(); } + + @Override + public MiniAppConfig getByAppid(String appid) { + return null; + } }; } } diff --git a/zlt-business/file-center/src/main/java/com/central/file/model/FileInfo.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/FileInfo.java similarity index 86% rename from zlt-business/file-center/src/main/java/com/central/file/model/FileInfo.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/FileInfo.java index 2e7e300b..33065a5e 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/model/FileInfo.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/FileInfo.java @@ -1,59 +1,61 @@ -package com.central.file.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import com.baomidou.mybatisplus.extension.activerecord.Model; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.io.Serializable; -import java.util.Date; - -/** - * file实体类 - * - * @author 作者 owen E-mail: 624191343@qq.com - */ -@Data -@EqualsAndHashCode(callSuper = false) -@TableName("file_info") -public class FileInfo extends Model { - private static final long serialVersionUID = -1438078028040922174L; - - @TableId - private String id; - /** - * 原始文件名 - */ - private String name; - /** - * 是否图片 - */ - private Boolean isImg; - /** - * 上传文件类型 - */ - private String contentType; - /** - * 文件大小 - */ - private long size; - /** - * 冗余字段 - */ - private String path; - /** - * oss访问路径 oss需要设置公共读 - */ - private String url; - /** - * FileType字段 - */ - private String source; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; -} +package com.central.common.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * file实体类 + * + * @author 作者 owen E-mail: 624191343@qq.com + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("file_info") +@Getter +@Setter +public class FileInfo extends Model { + + @TableId + private String id; + /** + * 原始文件名 + */ + private String name; + /** + * 是否图片 + */ + private Boolean isImg; + /** + * 上传文件类型 + */ + private String contentType; + /** + * 文件大小 + */ + private long size; + /** + * 冗余字段 + */ + private String path; + /** + * oss访问路径 oss需要设置公共读 + */ + private String url; + /** + * FileType字段 + */ + private String source; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/MiniAppConfig.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/MiniAppConfig.java new file mode 100644 index 00000000..96c2948c --- /dev/null +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/MiniAppConfig.java @@ -0,0 +1,29 @@ +package com.central.common.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +/** + * @author lsl + * 系统小程序 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("mini_app_config") +public class MiniAppConfig { + private Long id; + private String appCode; + private String appid; + private String secret; + private String name; + private Integer status; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; +} diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/PageResult.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/PageResult.java index 5404fc23..056c22c2 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/PageResult.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/PageResult.java @@ -1,13 +1,13 @@ package com.central.common.model; -import java.io.Serializable; -import java.util.List; - import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import java.io.Serializable; +import java.util.List; + /** * 分页实体类 * @@ -26,7 +26,7 @@ public class PageResult implements Serializable { /** * 是否成功:0 成功、1 失败 */ - private int code; + private int resp_code; /** * 当前页结果集 */ diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/Result.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/Result.java index 13682bda..972419e4 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/Result.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/Result.java @@ -14,7 +14,7 @@ import java.io.Serializable; @AllArgsConstructor public class Result implements Serializable { - private T datas; + private T data; private Integer resp_code; private String resp_msg; diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java index bd90f82a..4140294f 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java @@ -1,17 +1,17 @@ package com.central.common.model; -import java.util.List; -import java.util.Set; - import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; +import java.util.List; +import java.util.Set; + /** * @author zlt - * 用户实体 + * 系统用户实体 */ @Data @EqualsAndHashCode(callSuper = false) @@ -28,6 +28,7 @@ public class SysUser extends SuperEntity { private Boolean enabled; private String type; private String openId; + private String unionId; private Long creatorId; @TableLogic private boolean isDel; diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/properties/TenantProperties.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/properties/TenantProperties.java index e749a1f3..2c36415f 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/properties/TenantProperties.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/properties/TenantProperties.java @@ -1,11 +1,10 @@ package com.central.common.properties; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -13,8 +12,7 @@ import java.util.List; * @author zlt * @date 2019/8/5 */ -@Setter -@Getter +@Data @ConfigurationProperties(prefix = "zlt.tenant") @RefreshScope public class TenantProperties { @@ -24,13 +22,27 @@ public class TenantProperties { private Boolean enable = false; /** - * 配置不进行多租户隔离的表名 + * 忽略租户的表名 */ - private List ignoreTables = new ArrayList<>(); + private List ignoreTables = Arrays.asList( + "sys_user", + "sys_role_user", + "sys_role_menu" + ); /** - * 配置不进行多租户隔离的sql - * 需要配置mapper的全路径如:com.central.user.mapper.SysUserMapper.findList + * 忽略租户的SQL */ - private List ignoreSqls = new ArrayList<>(); + private List ignoreSqls = Arrays.asList( + "com.central.user.mapper.SysRoleMapper.findAll", + "com.central.user.mapper.SysUserRoleMapper.findRolesByUserIds" + ); + + /** + * 不可忽略租户的SQL + */ + private List noIgnoreSqls = Arrays.asList( + "com.central.user.mapper.SysRoleMapper.findAll", + "com.central.user.mapper.SysUserRoleMapper.findRolesByUserIds" + ); } diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/FileToMultipartFileConverterUtil.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/FileToMultipartFileConverterUtil.java new file mode 100644 index 00000000..e5457b80 --- /dev/null +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/FileToMultipartFileConverterUtil.java @@ -0,0 +1,48 @@ +package com.central.common.utils; + +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +public class FileToMultipartFileConverterUtil { + + public static MultipartFile convert(File file) throws IOException { + String originalFilename = file.getName(); + String contentType = "application/octet-stream"; // 默认MIME类型,可以根据文件类型设置 + byte[] content = loadFileContent(file); + + return new MockMultipartFile( + "file", // 参数名,即中的name属性值 + originalFilename, + contentType, + content + ); + } + + private static byte[] loadFileContent(File file) throws IOException { + try (FileInputStream inputStream = new FileInputStream(file)) { + // 创建一个足够大的字节数组来存储文件内容 + byte[] content = new byte[(int) file.length()]; + int bytesRead = inputStream.read(content); + if (bytesRead != file.length()) { + throw new IOException("Could not read the entire file into the byte array."); + } + return content; + } + } + + /*public static void main(String[] args) { + // 示例用法 + File file = new File("path/to/your/file.txt"); + try { + MultipartFile multipartFile = convert(file); + // 现在你可以使用multipartFile对象,例如在Spring MVC控制器中处理文件上传 + System.out.println("File converted to MultipartFile successfully."); + } catch (IOException e) { + e.printStackTrace(); + } + }*/ +} diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/RSAUtil.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/RSAUtil.java new file mode 100644 index 00000000..7f1014ec --- /dev/null +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/RSAUtil.java @@ -0,0 +1,279 @@ +package com.central.common.utils; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; + +import javax.crypto.Cipher; +import java.io.ByteArrayOutputStream; +import java.security.*; +import java.security.interfaces.RSAPrivateKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +/** + * RSA加解密、创建与校验签名的工具类 + */ +@Slf4j +public class RSAUtil { + public static final String PUBLIC_KEY = "PUBLIC_KEY"; + public static final String PRIVATE_KEY = "PRIVATE_KEY"; + + private static final Base64.Encoder base64Encoder = Base64.getEncoder(); + private static final Base64.Decoder base64Decoder = Base64.getDecoder(); + + private static final String ALGORITHM = "RSA/ECB/PKCS1Padding"; + /** + * 签名算法 + */ + private static final String SIGN_TYPE = "SHA1withRSA"; + /** + * 密钥长度 + */ + private static final Integer KEY_LENGTH = 1024; + + /** + * RSA最大加密明文大小 + */ + private static final int MAX_ENCRYPT_BLOCK = 117; + /** + * RSA最大解密密文大小 + */ + private static final int MAX_DECRYPT_BLOCK = 128; + public static PublicKey publicKey; + public static PrivateKey privateKey; + + static { + Map map = null; + try { + map = genKeyPair(); + publicKey = (PublicKey) map.get(PUBLIC_KEY); + privateKey = (PrivateKey) map.get(PRIVATE_KEY); + } catch (Exception e) { + e.printStackTrace(); + } + } + /** + * 生成秘钥对,公钥和私钥 + * + * @return 秘钥键值对 + * @throws Exception 创建秘钥对异常 + */ + public static Map genKeyPair() throws Exception { + Map keyMap = new HashMap<>(); + String pubKey = + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGu7lYGfEtMICO8kREJrObu0Hy" + + "pF7R9iEIefyxApmB6wJ/y3Rg/eBO6kLDCo18hYZ3ZNxKp5CMymZvXDh5j+sd7IHm" + + "tUh6sEZzpXExQJIzT8gA1SULd+iXe4V9zt2AcbROIi94vA6lOfmtON28Ex+uAlLK" + + "N/iJDXFFXdEOmfdqhwIDAQAB"; + Base64.Decoder decoder = Base64.getDecoder(); + byte[] keyBytes = decoder.decode(pubKey); + X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); + KeyFactory kf = KeyFactory.getInstance("RSA"); + PublicKey publicKey = kf.generatePublic(spec); + String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIa7uVgZ8S0wgI7y" + + "REQms5u7QfKkXtH2IQh5/LECmYHrAn/LdGD94E7qQsMKjXyFhndk3EqnkIzKZm9c" + + "OHmP6x3sgea1SHqwRnOlcTFAkjNPyADVJQt36Jd7hX3O3YBxtE4iL3i8DqU5+a04" + + "3bwTH64CUso3+IkNcUVd0Q6Z92qHAgMBAAECgYAogZGkahA3DMjpsO5TKut+m1ql" + + "T0Nujje6K6qLsQNjqrrSnuE7M7hXIVi2+Jo24JHfnUQZca0klskbG7ei3GDL6eEb" + + "Qm3NlJ84bxDQUOy6SSiqZHYKP0Yvwgk3uR8OM6hjnv6c7b5HPlvp00DuMlwkw+ST" + + "Ng5ErJrgx6g7Dte1KQJBAN2Bp1HQ804cnqZyEfQLjx/uf1+BKGXsEjf25u5WZCZ5" + + "slxIbtkhtG61L4z7uOLxBKyixR37YvM94HNxLQ2+7E0CQQCbttyVTpnXRXrzhUT7" + + "W8ML8BE5jiCqbU/Y1VAm7Sp5D3SOLDbMZKG8lV6duUYSdoYY7ZrqO8qU6XWXbWxj" + + "r4wjAkA9lMobqOe7k6FXzObI3l3QFtI6jwHYNCVsgav6HvKA79xyY4DNxN0Q2jZ6" + + "D5F7Jl6SUD5U84qy7UT1U0WfSLERAkB3zv3v33dc/De60SqfYB41vDP0ndeiadMK" + + "2i3+lXKdjPe4QGq1XyRWjnMrVheFMy7AVWlhmjmn0+1HYskH9lUTAkBRlC0bbsMh" + + "ttwtWnWvTjgCynymlKYKmzakBllknkokCE3cjefS5BoG0yAavZUJ4bozaTBVRcs5" + + "JN1IsgxqgsOq"; + byte[] decoded = decoder.decode(privateKey); + + RSAPrivateKey rsaPrivateKey = + (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); + keyMap.put(PUBLIC_KEY, publicKey); + keyMap.put(PRIVATE_KEY, rsaPrivateKey); + return keyMap; + } + + /** + * 公钥加密 + * + * @param data 加密前数据 + * @param publicKey 公钥 + * @return 加密后数据 + * @throws Exception 加密异常 + */ + public static byte[] encryptByPublicKey(byte[] data, PublicKey publicKey) throws Exception { + // 加密数据,分段加密 + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + int inputLength = data.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offset = 0; + byte[] cache; + int i = 0; + while (inputLength - offset > 0) { + if (inputLength - offset > MAX_ENCRYPT_BLOCK) { + cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offset, inputLength - offset); + } + out.write(cache, 0, cache.length); + i++; + offset = i * MAX_ENCRYPT_BLOCK; + } + byte[] encryptedData = out.toByteArray(); + out.close(); + return encryptedData; + } + + public static byte[] encryptByPublicKey(byte[] data, String publicKeyBase64Encoded) throws Exception { + return encryptByPublicKey(data, parseString2PublicKey(publicKeyBase64Encoded)); + } + + /** + * 私钥解密 + * + * @param data 解密前数据 + * @param privateKey 私钥 + * @return 解密后数据 + * @throws Exception 解密异常 + */ + public static byte[] decryptByPrivateKey(byte[] data, PrivateKey privateKey) { + // 解密数据,分段解密 + try{ + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.DECRYPT_MODE, privateKey); + int inputLength = data.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offset = 0; + byte[] cache; + int i = 0; + while (inputLength - offset > 0) { + if (inputLength - offset > MAX_DECRYPT_BLOCK) { + cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offset, inputLength - offset); + } + out.write(cache); + i++; + offset = i * MAX_DECRYPT_BLOCK; + } + byte[] decryptedData = out.toByteArray(); + out.close(); + return decryptedData; + }catch (Exception e){ + log.info("解密异常:{}",e.getMessage()); + e.printStackTrace(); + return null; + } + + } + + public static byte[] decryptByPrivateKey(byte[] data, String privateKeyBase64Encoded) throws Exception { + return decryptByPrivateKey(data, parseString2PrivateKey(privateKeyBase64Encoded)); + } + + /** + * 创建签名 + * + * @param source 要签名的信息 + * @param privateKey 私钥 + * @return 签名 + * @throws Exception 签名异常 + */ + public static byte[] createSign(String source, PrivateKey privateKey) throws Exception { + Signature signet = Signature.getInstance(SIGN_TYPE); + signet.initSign(privateKey); + signet.update(source.getBytes()); + return signet.sign(); + } + + public static byte[] createSign(String source, String privateKeyBase64Encoded) throws Exception { + return createSign(source, parseString2PrivateKey(privateKeyBase64Encoded)); + } + + /** + * 校验签名 + * + * @param expected 期望信息 + * @param sign 签名 + * @param publicKey 公钥 + * @return 结果 + * @throws Exception 校验异常 + */ + public static boolean checkSign(String expected, byte[] sign, PublicKey publicKey) throws Exception { + Signature signetCheck = Signature.getInstance(SIGN_TYPE); + signetCheck.initVerify(publicKey); + signetCheck.update(expected.getBytes()); + return signetCheck.verify(sign); + } + + public static boolean checkSign(String expected, byte[] sign, String publicKeyBase64Encoded) throws Exception { + return checkSign(expected, sign, parseString2PublicKey(publicKeyBase64Encoded)); + } + + /** + * 将base64格式的公钥转换为对象 + * + * @param publicKeyBase64Encoded base64的公钥 + * @return 公钥 + * @throws Exception 转换异常 + */ + public static PublicKey parseString2PublicKey(String publicKeyBase64Encoded) throws Exception { + return KeyFactory.getInstance(ALGORITHM).generatePublic( + new X509EncodedKeySpec(base64Decoder.decode(publicKeyBase64Encoded))); + } + + /** + * 将base64格式的私钥转换为对象 + * + * @param privateKeyBase64Encoded base64的私钥 + * @return 私钥 + * @throws Exception 转换异常 + */ + public static PrivateKey parseString2PrivateKey(String privateKeyBase64Encoded) throws Exception { + return KeyFactory.getInstance(ALGORITHM).generatePrivate( + new PKCS8EncodedKeySpec(base64Decoder.decode(privateKeyBase64Encoded))); + } + public static String getEncData(String data) throws Exception { + String enc = Base64.getEncoder().encodeToString(RSAUtil.encryptByPublicKey(data.getBytes(), + publicKey)); + return StringUtils.replace(enc, "/", "%2F"); + } + // 单个解密 私钥 + public static String decryptOne(String des) { + String _imageName = StringUtils.replace(des, "%2F", "/"); + try { + return new String(RSAUtil.decryptByPrivateKey(Base64.getDecoder().decode(_imageName), (PrivateKey) RSAUtil.genKeyPair().get(RSAUtil.PRIVATE_KEY))); + } catch (Exception e) { + log.info("解密异常:{}",e.getMessage()); + e.printStackTrace(); + return null; + } + } + // 单个加密 公钥加密 + public static String encryptOne(String des) { + try { + return StringUtils.replace(Base64.getEncoder().encodeToString(RSAUtil.encryptByPublicKey(des.getBytes(), (PublicKey) RSAUtil.genKeyPair().get(RSAUtil.PUBLIC_KEY))) + , "/", "%2F"); + } catch (Exception e) { + log.info("加密异常:{}",e.getMessage()); + return null; + } + } + + public static String getDecData(String data) throws Exception { + String replace = StringUtils.replace(data, "%2F", "/"); + return new String(decryptByPrivateKey(Base64.getDecoder().decode(replace), privateKey)); + } + + + + public static void main(String[] args) { + System.out.println("公钥加密>>>>>>:" + encryptOne("慧谷测试")); + System.out.println("私钥解密>>>>>>:" + decryptOne("LBS9qzlDcBQeb+WLhGRKm5+zoQkPokrEdwejn1VZSmYPaLrAS2LUCbSHViZOfUcvql5j57dvMEXw5jhOu7775exptY%2FyHNTxld2PjmgTPg6If4EOFpD4z+YSuQQyTz4lWmKCQ7egP35qYvAyHUkG%2FyNEOSJUClQbrEfnj1OcL1s=")); + + } +} diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/StringUtils.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/StringUtils.java new file mode 100644 index 00000000..b877907e --- /dev/null +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/StringUtils.java @@ -0,0 +1,409 @@ +package com.central.common.utils; + +import org.apache.commons.lang.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class StringUtils extends org.apache.commons.lang.StringUtils { + static final String HEX_FORMAT = "%02x"; + private static final Logger logger = LoggerFactory.getLogger(StringUtils.class); + private static final char SEPARATOR = '_'; + private static final String CHARSET_NAME = "UTF-8"; + + public StringUtils() { + } + + public static byte[] getBytes(String str) { + if (str != null) { + try { + return str.getBytes("UTF-8"); + } catch (UnsupportedEncodingException var2) { + return null; + } + } else { + return null; + } + } + + public static String toString(byte[] bytes) { + try { + return new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException var2) { + return ""; + } + } + + public static boolean inString(String str, String... strs) { + if (str != null) { + String[] var2 = strs; + int var3 = strs.length; + + for(int var4 = 0; var4 < var3; ++var4) { + String s = var2[var4]; + if (str.equals(trim(s))) { + return true; + } + } + } + + return false; + } + + public static String replaceHtml(String html) { + if (isBlank(html)) { + return ""; + } else { + String regEx = "<.+?>"; + Pattern p = Pattern.compile(regEx); + Matcher m = p.matcher(html); + String s = m.replaceAll(""); + return s; + } + } + + public static String replaceMobileHtml(String html) { + return html == null ? "" : html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>"); + } + + public static String toHtml(String txt) { + return txt == null ? "" : ""; + } + + public static String abbr(String str, int length) { + if (str == null) { + return ""; + } else { + try { + StringBuilder sb = new StringBuilder(); + int currentLength = 0; + char[] var4 = replaceHtml(StringEscapeUtils.unescapeHtml(str)).toCharArray(); + int var5 = var4.length; + + for(int var6 = 0; var6 < var5; ++var6) { + char c = var4[var6]; + currentLength += String.valueOf(c).getBytes("GBK").length; + if (currentLength > length - 3) { + sb.append("..."); + break; + } + + sb.append(c); + } + + return sb.toString(); + } catch (UnsupportedEncodingException var8) { + logger.error("出现异常", var8); + return ""; + } + } + } + + public static String abbr2(String param, int length) { + if (param == null) { + return ""; + } else { + StringBuffer result = new StringBuffer(); + int n = 0; + boolean isCode = false; + boolean isHTML = false; + + for(int i = 0; i < param.length(); ++i) { + char temp = param.charAt(i); + if (temp == '<') { + isCode = true; + } else if (temp == '&') { + isHTML = true; + } else if (temp == '>' && isCode) { + --n; + isCode = false; + } else if (temp == ';' && isHTML) { + isHTML = false; + } + + try { + if (!isCode && !isHTML) { + n += String.valueOf(temp).getBytes("GBK").length; + } + } catch (UnsupportedEncodingException var12) { + logger.error("出现异常", var12); + } + + if (n > length - 3) { + result.append("..."); + break; + } + + result.append(temp); + } + + String temp_result = result.toString().replaceAll("(>)[^<>]*(]*/?>", ""); + temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)", "$2"); + Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>"); + Matcher m = p.matcher(temp_result); + ArrayList endHTML = new ArrayList(); + + while(m.find()) { + endHTML.add(m.group(1)); + } + + for(int i = endHTML.size() - 1; i >= 0; --i) { + result.append(""); + } + + return result.toString(); + } + } + + public static Double toDouble(Object val) { + if (val == null) { + return 0.0D; + } else { + try { + return Double.valueOf(trim(val.toString())); + } catch (Exception var2) { + return 0.0D; + } + } + } + + public static Float toFloat(Object val) { + return toDouble(val).floatValue(); + } + + public static Long toLong(Object val) { + return toDouble(val).longValue(); + } + + public static Integer toInteger(Object val) { + return toLong(val).intValue(); + } + + public static boolean toBoolean(String val) { + return Boolean.parseBoolean(val); + } + + public static String getMessage(String code, Object[] args) { + return ""; + } + + public static BigDecimal toBigDecimal(String str){ + return new BigDecimal(str).setScale(7, BigDecimal.ROUND_HALF_UP); + } + + public static String getRemoteAddr(HttpServletRequest request) { + String remoteAddr = request.getHeader("X-Real-IP"); + if (isNotBlank(remoteAddr)) { + remoteAddr = request.getHeader("X-Forwarded-For"); + } else if (isNotBlank(remoteAddr)) { + remoteAddr = request.getHeader("Proxy-Client-IP"); + } else if (isNotBlank(remoteAddr)) { + remoteAddr = request.getHeader("WL-Proxy-Client-IP"); + } + + return remoteAddr != null ? remoteAddr : request.getRemoteAddr(); + } + + public static String toCamelCase(String s) { + if (s == null) { + return null; + } else { + s = s.toLowerCase(); + StringBuilder sb = new StringBuilder(s.length()); + boolean upperCase = false; + + for(int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (c == '_') { + upperCase = true; + } else if (upperCase) { + sb.append(Character.toUpperCase(c)); + upperCase = false; + } else { + sb.append(c); + } + } + + return sb.toString(); + } + } + + public static String toCapitalizeCamelCase(String s) { + if (s == null) { + return null; + } else { + s = toCamelCase(s); + return s.substring(0, 1).toUpperCase() + s.substring(1); + } + } + + public static String toUnderScoreCase(String s) { + if (s == null) { + return null; + } else { + StringBuilder sb = new StringBuilder(); + boolean upperCase = false; + + for(int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + boolean nextUpperCase = true; + if (i < s.length() - 1) { + nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); + } + + if (i > 0 && Character.isUpperCase(c)) { + if (!upperCase || !nextUpperCase) { + sb.append('_'); + } + + upperCase = true; + } else { + upperCase = false; + } + + sb.append(Character.toLowerCase(c)); + } + + return sb.toString(); + } + } + + public static String jsGetVal(String objectString) { + StringBuilder result = new StringBuilder(); + StringBuilder val = new StringBuilder(); + String[] vals = split(objectString, "."); + + for(int i = 0; i < vals.length; ++i) { + val.append("." + vals[i]); + result.append("!" + val.substring(1) + "?'':"); + } + + result.append(val.substring(1)); + return result.toString(); + } + + public static String string2Unicode(String string) { + StringBuffer unicode = new StringBuffer(); + + for(int i = 0; i < string.length(); ++i) { + char c = string.charAt(i); + unicode.append("\\u" + Integer.toHexString(c)); + } + + return unicode.toString(); + } + + public static String unicode2String(String unicode) { + StringBuffer string = new StringBuffer(); + String[] hex = unicode.split("\\\\u"); + + for(int i = 1; i < hex.length; ++i) { + int data = Integer.parseInt(hex[i], 16); + string.append((char)data); + } + + return string.toString(); + } + + public static String lengthFix(String text, int length, char ch, boolean end) { + if (text == null) { + text = ""; + } + + int tempLength = text.getBytes().length; + if (length == tempLength) { + return text; + } else if (length <= tempLength) { + return end ? new String(text.getBytes(), 0, length) : new String(text.getBytes(), tempLength - length, length); + } else { + char[] fix = new char[length - tempLength]; + + for(int i = 0; i < fix.length; ++i) { + fix[i] = ch; + } + + StringBuffer buffer = new StringBuffer(text); + if (end) { + buffer = buffer.append(fix); + } else { + buffer = buffer.insert(0, fix); + } + + return buffer.toString(); + } + } + + public static String lengthFix(String text, int length, String ch, boolean end) { + return lengthFix(text, length, ch.charAt(0), end); + } + + public static String bytesToHexStr(byte[] b) { + return bytesToHexStr(b, 0, b.length); + } + + public static String bytesToHexStr(byte[] b, int start, int len) { + if (start < b.length && b != null && b.length != 0) { + StringBuffer str = new StringBuffer(); + + for(int i = start; i < start + len; ++i) { + str.append(String.format("%02x", b[i])); + } + + return str.toString(); + } else { + return ""; + } + } + + public static byte[] hexStrToBytes(String str) { + if (str.length() % 2 != 0) { + str = "0" + str; + } + + byte[] temp = new byte[str.length() / 2]; + + for(int i = 0; i < str.length(); i += 2) { + temp[i / 2] = (byte)(Byte.parseByte(str.substring(i, i + 1), 16) * 16 + Byte.parseByte(str.substring(i + 1, i + 2), 16)); + } + + return temp; + } + + public static void hexStrToBytes(String str, byte[] b, int from) { + if (str.length() % 2 != 0) { + str = "0" + str; + } + + hexStrToBytes(str, b, from, str.length() / 2); + } + + public static void hexStrToBytes(String str, byte[] b, int from, int length) { + if (str.length() % 2 != 0) { + str = "0" + str; + } + + for(int i = 0; i < Math.min(str.length(), length * 2) && from + i / 2 < b.length; i += 2) { + b[from + i / 2] = (byte)(Byte.parseByte(str.substring(i, i + 1), 16) * 16 + Byte.parseByte(str.substring(i + 1, i + 2), 16)); + } + + } + + + public static Predicate distinctByKey(Function keyExtractor) { + Map seen = new ConcurrentHashMap<>(); + return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/pom.xml b/zlt-commons/zlt-common-spring-boot-starter/pom.xml index 0b6712e9..eeb4f91c 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-common-spring-boot-starter/pom.xml @@ -13,6 +13,7 @@ com.zlt zlt-common-core + 6.0.0 - \ No newline at end of file + diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java index f1f875f8..f6aa1b15 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java +++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java @@ -31,6 +31,7 @@ public class LoginUserFilter extends OncePerRequestFilter { FilterChain filterChain) throws IOException, ServletException { try { LoginAppUser user = LoginUserUtils.getCurrentUser(request, false); + logger.debug(request.toString()); LoginUserContextHolder.setUser(user); filterChain.doFilter(request, response); } finally { diff --git a/zlt-commons/zlt-db-spring-boot-starter/pom.xml b/zlt-commons/zlt-db-spring-boot-starter/pom.xml index 2d6cf775..5adb31a2 100644 --- a/zlt-commons/zlt-db-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-db-spring-boot-starter/pom.xml @@ -32,5 +32,12 @@ spring-boot-configuration-processor true + + + com.github.yulichang + mybatis-plus-join + 1.2.4 + + diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java index d5047549..0b9ef383 100644 --- a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java +++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/MybatisPlusAutoConfigure.java @@ -58,7 +58,7 @@ public class MybatisPlusAutoConfigure { //是否开启多租户隔离 if (enableTenant) { CustomTenantInterceptor tenantInterceptor = new CustomTenantInterceptor( - tenantLineHandler, tenantProperties.getIgnoreSqls()); + tenantLineHandler, tenantProperties.getIgnoreSqls(),tenantProperties.getNoIgnoreSqls()); mpInterceptor.addInnerInterceptor(tenantInterceptor); } if(dataScopeProperties.getEnabled()){ diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/TenantAutoConfigure.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/TenantAutoConfigure.java index 8778dd6d..77d91237 100644 --- a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/TenantAutoConfigure.java +++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/TenantAutoConfigure.java @@ -1,7 +1,9 @@ package com.central.db.config; import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler; +import com.central.common.context.LoginUserContextHolder; import com.central.common.context.TenantContextHolder; +import com.central.common.model.LoginAppUser; import com.central.common.properties.TenantProperties; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.NullValue; @@ -29,6 +31,12 @@ public class TenantAutoConfigure { */ @Override public Expression getTenantId() { + // 判断当前用户是否为超级管理员 + if (isSuperAdmin()) { + // 超级管理员返回Null,不加租户条件 + return new NullValue(); + } + String tenant = TenantContextHolder.getTenant(); if (tenant != null) { return new StringValue(TenantContextHolder.getTenant()); @@ -48,4 +56,12 @@ public class TenantAutoConfigure { } }; } + + private boolean isSuperAdmin() { + // 你可以通过ThreadLocal、SecurityContext、LoginUserContextHolder等获取当前用户角色 + // 例如: + LoginAppUser user = LoginUserContextHolder.getUser(); + //@TODO 暂定admin和mgnt为系统管理员 + return user != null && (user.getUsername().equals("admin") || user.getUsername().equals("mgnt")); + } } diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/interceptor/CustomTenantInterceptor.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/interceptor/CustomTenantInterceptor.java index 86e84e46..3b5925d4 100644 --- a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/interceptor/CustomTenantInterceptor.java +++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/interceptor/CustomTenantInterceptor.java @@ -23,10 +23,12 @@ import java.util.List; */ public class CustomTenantInterceptor extends TenantLineInnerInterceptor { private List ignoreSqls; + private List noIgnoreSqls; - public CustomTenantInterceptor(TenantLineHandler tenantLineHandler, List ignoreSqls) { + public CustomTenantInterceptor(TenantLineHandler tenantLineHandler, List ignoreSqls, List noIgnoreSqls) { super(tenantLineHandler); this.ignoreSqls = ignoreSqls; + this.noIgnoreSqls = noIgnoreSqls; } @Override @@ -35,10 +37,17 @@ public class CustomTenantInterceptor extends TenantLineInnerInterceptor { if (isIgnoreMappedStatement(ms.getId())) { return; } - super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql); + if (isNoIgnoreMappedStatement(ms.getId())) { + super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql); + } + } private boolean isIgnoreMappedStatement(String msId) { return ignoreSqls.stream().anyMatch((e) -> e.equalsIgnoreCase(msId)); } + + private boolean isNoIgnoreMappedStatement(String msId) { + return noIgnoreSqls.stream().anyMatch((e) -> e.equalsIgnoreCase(msId)); + } } diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/mapper/SuperMapper.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/mapper/SuperMapper.java index f93bcaca..980f49d9 100644 --- a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/mapper/SuperMapper.java +++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/mapper/SuperMapper.java @@ -1,12 +1,12 @@ package com.central.db.mapper; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.github.yulichang.base.MPJBaseMapper; /** * mapper 父类,注意这个类不要让 mp 扫描到!! * @author zlt */ -public interface SuperMapper extends BaseMapper { +public interface SuperMapper extends MPJBaseMapper { // 这里可以放一些公共的方法 } diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/utils/PageUtils.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/utils/PageUtils.java new file mode 100644 index 00000000..086793ba --- /dev/null +++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/utils/PageUtils.java @@ -0,0 +1,82 @@ +package com.central.db.utils; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import lombok.Data; +import lombok.ToString; + +import java.io.Serializable; +import java.util.List; + +/** + * 分页工具类 + * + * @author lishilin + * @date 2020/03/02 + */ +@ToString +@Data +public class PageUtils implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 总记录数 + */ + private int totalCount; + /** + * 每页记录数 + */ + private int pageSize; + /** + * 总页数 + */ + private int totalPage; + /** + * 当前页数 + */ + private int currPage; + /** + * 列表数据 + */ + private List list; + + /** + * 分页 + * @param list 列表数据 + * @param totalCount 总记录数 + * @param pageSize 每页记录数 + * @param currPage 当前页数 + */ + public PageUtils(List list, int totalCount, int pageSize, int currPage) { + this.list = list; + this.totalCount = totalCount; + this.pageSize = pageSize; + this.currPage = currPage; + this.totalPage = (int)Math.ceil((double)totalCount/pageSize); + } + + public PageUtils(){ + + } + + public PageUtils(List records, int total, int size, int current, boolean format) { + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + /** + * 分页 + */ + public PageUtils(IPage page) { + this.list = page.getRecords(); + this.totalCount = (int)page.getTotal(); + this.pageSize = (int) page.getSize(); + this.currPage = (int) page.getCurrent(); + this.totalPage = (int)page.getPages(); + } + +} diff --git a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/utils/SearchBuilder.java b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/utils/SearchBuilder.java index c119600c..efea8ce7 100644 --- a/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/utils/SearchBuilder.java +++ b/zlt-commons/zlt-elasticsearch-spring-boot-starter/src/main/java/com/central/es/utils/SearchBuilder.java @@ -232,7 +232,7 @@ public class SearchBuilder { SearchHits searchHits = response.getHits(); long totalCnt = searchHits.getTotalHits().value; List list = getList(searchHits); - return PageResult.builder().data(list).code(0).count(totalCnt).build(); + return PageResult.builder().data(list).resp_code(0).count(totalCnt).build(); } /** diff --git a/zlt-commons/zlt-oss-spring-boot-starter/pom.xml b/zlt-commons/zlt-oss-spring-boot-starter/pom.xml index 099920f9..9902292f 100644 --- a/zlt-commons/zlt-oss-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-oss-spring-boot-starter/pom.xml @@ -34,5 +34,18 @@ spring-boot-configuration-processor true + + + com.qcloud + cos_api + 5.6.227 + + + + com.aliyun.oss + aliyun-sdk-oss + 3.17.4 + + diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/config/OssAutoConfigure.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/config/OssAutoConfigure.java index 419e6074..2b5adb46 100644 --- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/config/OssAutoConfigure.java +++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/config/OssAutoConfigure.java @@ -1,20 +1,20 @@ package com.central.oss.config; import com.central.oss.properties.FileServerProperties; +import com.central.oss.template.CosTemplate; import com.central.oss.template.FdfsTemplate; +import com.central.oss.template.OssTemplate; import com.central.oss.template.S3Template; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Import; /** - * @author zlt - * @date 2021/2/13 + * @author lsl + * @date 2025/1/13 *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 */ @EnableConfigurationProperties(FileServerProperties.class) -@Import({FdfsTemplate.class, S3Template.class}) +@Import({FdfsTemplate.class, S3Template.class, CosTemplate.class, OssTemplate.class}) public class OssAutoConfigure { } diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/CosProperties.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/CosProperties.java new file mode 100644 index 00000000..0162e7d6 --- /dev/null +++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/CosProperties.java @@ -0,0 +1,41 @@ +package com.central.oss.properties; + +import lombok.Getter; +import lombok.Setter; + +/** + * cos 协议配置 + * + * @author lsl + * @date 2025/1/13 + *

+ */ +@Setter +@Getter +public class CosProperties { + + /** + * 用户名 + */ + private String secretId; + /** + * 密码 + */ + private String secretKey; + /** + * bucket名称 + */ + private String bucketName; + /** + * + */ + private String endpoint; + /** + * 区域 + */ + private String region; + /** + * path-style + */ + private Boolean pathStyleAccessEnabled = true; +} diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FileServerProperties.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FileServerProperties.java index 565ef7b7..5132db5c 100644 --- a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FileServerProperties.java +++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/FileServerProperties.java @@ -18,6 +18,8 @@ public class FileServerProperties { public static final String PREFIX = "zlt.file-server"; public static final String TYPE_FDFS = "fastdfs"; public static final String TYPE_S3 = "s3"; + public static final String TYPE_COS = "cos"; + public static final String TYPE_OSS = "oss"; /** * 为以下2个值,指定不同的自动化配置 @@ -35,4 +37,14 @@ public class FileServerProperties { * fastDFS配置 */ FdfsProperties fdfs = new FdfsProperties(); + + /** + * cos 配置 + */ + CosProperties cos = new CosProperties(); + + /** + * cos 配置 + */ + OssProperties oss = new OssProperties(); } diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/OssProperties.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/OssProperties.java new file mode 100644 index 00000000..f74fdeb8 --- /dev/null +++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/properties/OssProperties.java @@ -0,0 +1,41 @@ +package com.central.oss.properties; + +import lombok.Getter; +import lombok.Setter; + +/** + * oss 协议配置 + * + * @author lsl + * @date 2025/1/13 + *

+ */ +@Setter +@Getter +public class OssProperties { + + /** + * 用户名 + */ + private String secretId; + /** + * 密码 + */ + private String secretKey; + /** + * bucket名称 + */ + private String bucketName; + /** + * + */ + private String endpoint; + /** + * 区域 + */ + private String region; + /** + * path-style + */ + private Boolean pathStyleAccessEnabled = true; +} diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/CosTemplate.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/CosTemplate.java new file mode 100644 index 00000000..dfbf65f7 --- /dev/null +++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/CosTemplate.java @@ -0,0 +1,183 @@ +package com.central.oss.template; + +import com.central.oss.model.ObjectInfo; +import com.central.oss.properties.FileServerProperties; +import com.qcloud.cos.COSClient; +import com.qcloud.cos.ClientConfig; +import com.qcloud.cos.auth.BasicCOSCredentials; +import com.qcloud.cos.auth.COSCredentials; +import com.qcloud.cos.http.HttpProtocol; +import com.qcloud.cos.model.COSObject; +import com.qcloud.cos.model.COSObjectInputStream; +import com.qcloud.cos.model.ObjectMetadata; +import com.qcloud.cos.model.PutObjectRequest; +import com.qcloud.cos.region.Region; +import com.qcloud.cos.utils.IOUtils; +import lombok.SneakyThrows; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.Calendar; + +/** + * cos 配置 + * + * @author lsl + * @date 2025/1/13 + *

+ */ +@ConditionalOnClass(COSClient.class) +@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_COS) +public class CosTemplate implements InitializingBean { + + private static final String DEF_CONTEXT_TYPE = "application/octet-stream"; + private static final String PATH_SPLIT = "/"; + + @Autowired + private FileServerProperties fileProperties; + + private COSClient cosClient; + + @Override + public void afterPropertiesSet() { + + // 1. 初始化用户身份信息(secretId, secretKey)。 + COSCredentials cred = new BasicCOSCredentials(fileProperties.getCos().getSecretId(), fileProperties.getCos().getSecretKey()); + + // 2. 初始化地域配置 + Region region = new Region(fileProperties.getCos().getRegion()); + ClientConfig clientConfig = new ClientConfig(region); + clientConfig.setHttpProtocol(HttpProtocol.https); + + // 3. 生成 cos 客户端 + this.cosClient = new COSClient(cred, clientConfig); + } + + @SneakyThrows + public ObjectInfo upload(String fileName, InputStream is) { + return upload(fileProperties.getCos().getBucketName(), fileName, is, is.available(), DEF_CONTEXT_TYPE); + } + + @SneakyThrows + public ObjectInfo upload(MultipartFile file) { + return upload(fileProperties.getCos().getBucketName(), file.getOriginalFilename(), file.getInputStream() + , ((Long)file.getSize()).intValue(), file.getContentType()); + } + + @SneakyThrows + public ObjectInfo upload(String bucketName, String fileName, InputStream is) { + return upload(bucketName, fileName, is, is.available(), DEF_CONTEXT_TYPE); + } + + /** + * 上传对象 + * @param bucketName bucket名称 + * @param objectName 对象名 + */ + public ObjectInfo upload(String bucketName, String objectName, InputStream is, int size, String contentType) { + ObjectMetadata objectMetadata = new ObjectMetadata(); + objectMetadata.setContentLength(size); + objectMetadata.setContentType(contentType); + PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, is, objectMetadata); + putObjectRequest.getRequestClientOptions().setReadLimit(size + 1); + + cosClient.putObject(putObjectRequest); + + ObjectInfo obj = new ObjectInfo(); + obj.setObjectPath(bucketName + PATH_SPLIT + objectName); + obj.setObjectUrl(fileProperties.getCos().getEndpoint() + PATH_SPLIT + obj.getObjectPath()); + return obj; + } + + /** + * 上传对象 + * @param objectName 对象名 + */ + public ObjectInfo upload(String objectName, InputStream is, int size, String contentType) { + ObjectMetadata objectMetadata = new ObjectMetadata(); + objectMetadata.setContentLength(size); + objectMetadata.setContentType(contentType); + PutObjectRequest putObjectRequest = new PutObjectRequest(fileProperties.getCos().getBucketName(), objectName, is, objectMetadata); + putObjectRequest.getRequestClientOptions().setReadLimit(size + 1); + + cosClient.putObject(putObjectRequest); + + ObjectInfo obj = new ObjectInfo(); + obj.setObjectPath(fileProperties.getCos().getBucketName() + PATH_SPLIT + objectName); + obj.setObjectUrl(fileProperties.getCos().getEndpoint() + PATH_SPLIT + obj.getObjectPath()); + return obj; + } + + public void delete(String objectName) { + delete(fileProperties.getCos().getBucketName(), objectName); + } + + public void delete(String bucketName, String objectName) { + cosClient.deleteObject(bucketName, objectName); + } + + /** + * 获取预览地址 + * @param bucketName bucket名称 + * @param objectName 对象名 + * @param expires 有效时间(分钟),最大7天有效 + * @return + */ + public String getViewUrl(String bucketName, String objectName, int expires) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.MINUTE, expires); + URL url = cosClient.generatePresignedUrl(bucketName, objectName, cal.getTime()); + return url.toString(); + } + + /** + * 获取预览地址 + * @param objectName 对象名 + * @param expires 有效时间(分钟),最大7天有效 + * @return + */ + public String getViewUrl(String objectName, int expires) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.MINUTE, expires); + URL url = cosClient.generatePresignedUrl(fileProperties.getCos().getBucketName(), objectName, cal.getTime()); + return url.toString(); + } + + /** + * 获取预览地址 + * @param objectName 对象名 + * @return + */ + public String getViewUrl(String objectName) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.MINUTE, 7); + URL url = cosClient.generatePresignedUrl(fileProperties.getCos().getBucketName(), objectName, cal.getTime()); + return url.toString(); + } + + public void out(String objectName, OutputStream os) { + out(fileProperties.getS3().getBucketName(), objectName, os); + } + + /** + * 输出对象 + * @param bucketName bucket名称 + * @param objectName 对象名 + * @param os 输出流 + */ + @SneakyThrows + public void out(String bucketName, String objectName, OutputStream os) { + COSObject cosObject = cosClient.getObject(bucketName, objectName); + try ( + COSObjectInputStream cosis = cosObject.getObjectContent(); + ) { + IOUtils.copy(cosis, os); + } + } +} diff --git a/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/OssTemplate.java b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/OssTemplate.java new file mode 100644 index 00000000..553e6b20 --- /dev/null +++ b/zlt-commons/zlt-oss-spring-boot-starter/src/main/java/com/central/oss/template/OssTemplate.java @@ -0,0 +1,217 @@ +package com.central.oss.template; + +import com.aliyun.oss.HttpMethod; +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import com.aliyun.oss.model.GeneratePresignedUrlRequest; +import com.aliyun.oss.model.OSSObject; +import com.aliyun.oss.model.ObjectMetadata; +import com.aliyun.oss.model.ObjectListing; +import com.aliyun.oss.model.OSSObjectSummary; +import com.aliyun.oss.model.PutObjectRequest; +import com.central.oss.model.ObjectInfo; +import com.central.oss.properties.FileServerProperties; +import lombok.SneakyThrows; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +/** + * cos 配置 + * + * @author lsl + * @date 2025/1/13 + *

+ */ +@ConditionalOnClass(OSS.class) +@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_OSS) +public class OssTemplate implements InitializingBean { + + private static final String DEF_CONTEXT_TYPE = "application/octet-stream"; + private static final String PATH_SPLIT = "/"; + private static final int DEFAULT_EXPIRE_TYPE = 60; + + @Autowired + private FileServerProperties fileProperties; + + private OSS ossClient; + + @Override + public void afterPropertiesSet() { + + // 生成 oss 客户端 + this.ossClient = new OSSClientBuilder() + .build(fileProperties.getOss().getEndpoint(), fileProperties.getOss().getSecretId(), fileProperties.getOss().getSecretKey()); + } + + @SneakyThrows + public ObjectInfo upload(String fileName, InputStream is) { + return upload(fileProperties.getOss().getBucketName(), fileName, is, is.available(), DEF_CONTEXT_TYPE); + } + + @SneakyThrows + public ObjectInfo upload(MultipartFile file) { + return upload(fileProperties.getOss().getBucketName(), file.getOriginalFilename(), file.getInputStream() + , ((Long)file.getSize()).intValue(), file.getContentType()); + } + + @SneakyThrows + public ObjectInfo upload(String bucketName, String fileName, InputStream is) { + return upload(bucketName, fileName, is, is.available(), DEF_CONTEXT_TYPE); + } + + /** + * 上传对象 + * @param bucketName bucket名称 + * @param objectName 对象名 + */ + public ObjectInfo upload(String bucketName, String objectName, InputStream is, int size, String contentType) { + ObjectMetadata objectMetadata = new ObjectMetadata(); + objectMetadata.setContentLength(size); + objectMetadata.setContentType(contentType); + PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, is, objectMetadata); + + ossClient.putObject(putObjectRequest); + + ObjectInfo obj = new ObjectInfo(); + obj.setObjectPath(objectName); + obj.setObjectUrl(getViewUrl(objectName)); + return obj; + } + + /** + * 上传对象 + * @param objectName 对象名 + */ + public ObjectInfo upload(String objectName, InputStream is, int size, String contentType) { + ObjectMetadata objectMetadata = new ObjectMetadata(); + objectMetadata.setContentLength(size); + objectMetadata.setContentType(contentType); + PutObjectRequest putObjectRequest = new PutObjectRequest(fileProperties.getOss().getBucketName(), objectName, is, objectMetadata); + + ossClient.putObject(putObjectRequest); + + ObjectInfo obj = new ObjectInfo(); + obj.setObjectPath(objectName); +// obj.setObjectUrl(fileProperties.getOss().getEndpoint() + PATH_SPLIT + obj.getObjectPath()); + //需要重新获取可访问带有认证信息的url + obj.setObjectUrl(getViewUrl(objectName)); + return obj; + } + + public void delete(String objectName) { + delete(fileProperties.getOss().getBucketName(), objectName); + } + + public void delete(String bucketName, String objectName) { + ossClient.deleteObject(bucketName, objectName); + } + + /** + * 获取预览地址 + * @param bucketName bucket名称 + * @param objectName 对象名 + * @param expires 有效时间(分钟),最大7天有效 + * @return + */ + public String getViewUrl(String bucketName, String objectName, int expires) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.MINUTE, expires); + URL url = ossClient.generatePresignedUrl(bucketName, objectName, cal.getTime()); + return url.toString(); + } + + /** + * 获取预览地址 + * @param objectName 对象名 + * @param expires 有效时间(分钟),最大7天有效 + * @return + */ + public String getViewUrl(String objectName, int expires) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.MINUTE, expires); + URL url = ossClient.generatePresignedUrl(fileProperties.getOss().getBucketName(), objectName, cal.getTime()); + return url.toString(); + } + + /** + * 获取缩略图预览地址 + * @param objectName 对象名 + * @return + */ + public String getViewUrl(String objectName,String style) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.MINUTE, DEFAULT_EXPIRE_TYPE); + if (style == null) { + style = "image/resize,m_fixed,w_100,h_90"; // 默认缩略图样式 + } + GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(fileProperties.getOss().getBucketName(), objectName, HttpMethod.GET); + req.setProcess(style); + req.setExpiration(cal.getTime()); + URL url = ossClient.generatePresignedUrl(req); + return url.toString(); + } + + /** + * 获取预览地址 + * @param objectName 对象名 + * @return + */ + public String getViewUrl(String objectName) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.MINUTE, DEFAULT_EXPIRE_TYPE); + URL url = ossClient.generatePresignedUrl(fileProperties.getOss().getBucketName(), objectName, cal.getTime()); + return url.toString(); + } + + public void out(String objectName, OutputStream os) { + out(fileProperties.getOss().getBucketName(), objectName, os); + } + + /** + * 输出对象 + * @param bucketName bucket名称 + * @param objectName 对象名 + * @param os 输出流 + */ + @SneakyThrows + public void out(String bucketName, String objectName, OutputStream os) { + OSSObject ossObject = ossClient.getObject(bucketName, objectName); + try ( + InputStream ossis = ossObject.getObjectContent(); + ) { +// IOUtils.copy(ossis, os); + } + } + + /** + * 获取指定bucket和前缀(目录)下的所有文件名 + * @param bucketName bucket名称 + * @param prefix 目录前缀(如 "folder/",可为空字符串表示根目录) + * @return 文件名列表 + */ + public List listFiles(String bucketName, String prefix) { + List fileNames = new ArrayList<>(); + ObjectListing objectListing = ossClient.listObjects(bucketName, prefix); + for (OSSObjectSummary summary : objectListing.getObjectSummaries()) { + fileNames.add(summary.getKey()); + } + return fileNames; + } + + /** + * 获取默认bucket下指定前缀的所有文件名 + */ + public List listFiles(String prefix) { + return listFiles(fileProperties.getOss().getBucketName(), prefix); + } +} diff --git a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml index 77295143..c693cfc1 100644 --- a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml @@ -15,8 +15,8 @@ com.zlt zlt-common-core + 6.0.0 - org.redisson redisson-spring-boot-starter diff --git a/zlt-commons/zlt-wechat-common-core/pom.xml b/zlt-commons/zlt-wechat-common-core/pom.xml new file mode 100644 index 00000000..8b89c53b --- /dev/null +++ b/zlt-commons/zlt-wechat-common-core/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + + com.zlt + zlt-commons + 6.0.0 + + + zlt-wechat-common-core + 微信核心功能模块 + + + + + + + com.github.binarywang + weixin-java-mp + 4.5.0 + + + + com.squareup.okhttp3 + okhttp + 4.9.1 + + + com.github.binarywang + weixin-java-miniapp + 4.6.0 + + + + com.github.binarywang + weixin-java-common + 4.6.0 + + + com.github.wechatpay-apiv3 + wechatpay-java + 0.2.15 + + + + + com.zlt + zlt-common-core + + + org.springframework + spring-context + + + org.projectlombok + lombok + + + org.springframework.data + spring-data-redis + + + com.zlt + zlt-db-spring-boot-starter + + + diff --git a/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/config/WechatProperties.java b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/config/WechatProperties.java new file mode 100644 index 00000000..4411ea60 --- /dev/null +++ b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/config/WechatProperties.java @@ -0,0 +1,138 @@ +package com.central.wechat.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Data +@ConfigurationProperties(prefix = "zlt.wechat") +public class WechatProperties { + /** + * 微信公众号配置 + */ + private Mp mp = new Mp(); + + /** + * 微信小程序配置 + */ + private MiniApp miniApp = new MiniApp(); + + /** + * 微信支付配置 + */ + private Pay pay = new Pay(); + + /** + * 分账配置 + */ + private ProfitSharing profitSharing = new ProfitSharing(); + + @Data + public static class Mp { + /** + * 微信公众号appId + */ + private String appId; + + /** + * 微信公众号appSecret + */ + private String appSecret; + + /** + * 微信公众号token + */ + private String token; + + /** + * 微信公众号aesKey + */ + private String aesKey; + + /** + * 微信公众号消息模板ID + */ + private TemplateConfig templateId = new TemplateConfig(); + } + + @Data + public static class TemplateConfig { + /** + * 支付成功通知模板ID + */ + private String paymentSuccess; + + /** + * 视频处理完成通知模板ID + */ + private String videoComplete; + + /** + * 视频处理失败通知模板ID + */ + private String videoFail; + } + + @Data + public static class MiniApp { + /** + * 小程序appId + */ + private String appId; + + /** + * 小程序appSecret + */ + private String appSecret; + } + + @Data + public static class Pay { + /** + * 商户号 + */ + private String mchId; + + /** + * 商户API密钥 + */ + private String mchKey; + + /** + * 商户证书序列号 + */ + private String mchSerialNo; + + /** + * 商户私钥文件路径 + */ + private String privateKeyPath; + + /** + * APIv3密钥 + */ + private String apiV3Key; + + /** + * 支付回调地址 + */ + private String notifyUrl; + } + + @Data + public static class ProfitSharing { + /** + * 是否启用分账 + */ + private boolean enabled = true; + + /** + * 是否启用异步处理 + */ + private boolean asyncEnabled = true; + + /** + * 异步处理线程池大小 + */ + private int asyncPoolSize = 5; + } +} diff --git a/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/entity/WechatConfig.java b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/entity/WechatConfig.java new file mode 100644 index 00000000..053f44b4 --- /dev/null +++ b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/entity/WechatConfig.java @@ -0,0 +1,121 @@ +package com.central.wechat.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +@Data +@TableName("wechat_config") +public class WechatConfig { + /** + * 主键ID + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 租户ID + */ + private String tenantId; + + /** + * 配置类型:MP-公众号,MINI-小程序,PAY-支付 + */ + private String type; + + /** + * 商户ID + */ + private String merchantId; + + /** + * 应用ID + */ + private String appId; + + /** + * 应用密钥 + */ + private String appSecret; + + /** + * 商户API密钥 + */ + private String mchKey; + + /** + * 商户证书序列号 + */ + private String mchSerialNo; + + /** + * 商户私钥文件路径 + */ + private String privateKeyPath; + + /** + * 商户私钥 + */ + private String privateKey; + + /** + * APIv3密钥 + */ + private String apiV3Key; + + /** + * 支付回调地址 + */ + private String notifyUrl; + + /** + * 微信公众号token + */ + private String token; + + /** + * 微信公众号aesKey + */ + private String aesKey; + + /** + * 支付成功通知模板ID + */ + private String paymentSuccessTemplateId; + + /** + * 视频处理完成通知模板ID + */ + private String videoCompleteTemplateId; + + /** + * 视频处理失败通知模板ID + */ + private String videoFailTemplateId; + + /** + * 是否启用分账 + */ + private Boolean profitSharingEnabled; + + /** + * 是否启用异步处理 + */ + private Boolean asyncEnabled; + + /** + * 异步处理线程池大小 + */ + private Integer asyncPoolSize; + + /** + * 状态:0-禁用,1-启用 + */ + private Integer status; + + /** + * 备注 + */ + private String remark; +} diff --git a/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/WechatConfigService.java b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/WechatConfigService.java new file mode 100644 index 00000000..6e31b516 --- /dev/null +++ b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/WechatConfigService.java @@ -0,0 +1,32 @@ +package com.central.wechat.feign; + +import com.central.common.constant.ServiceNameConstants; +import com.central.wechat.entity.WechatConfig; +import com.central.wechat.feign.fallback.WechatConfigServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author zlt + */ +@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = WechatConfigServiceFallbackFactory.class, dismiss404 = true) +public interface WechatConfigService { + /** + * feign rpc访问远程/wechat/config/{type}接口 + * 查询微信配置对象WechatConfig + * + * @param type + * @return + */ + @GetMapping(value = "/wechat/config/{type}") + WechatConfig getConfig(@PathVariable("type") String type,@RequestParam("tenantId") String tenantId); + + @GetMapping(value = "/wechat/config/app/{id}") + WechatConfig getConfigByAppId(@PathVariable("id") String appId); + + @GetMapping(value = "/wechat/config/serial/{serialNumber}") + WechatConfig getConfigBySerialNumber(@PathVariable("serialNumber") String serialNumber); + +} diff --git a/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/fallback/WechatConfigServiceFallbackFactory.java b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/fallback/WechatConfigServiceFallbackFactory.java new file mode 100644 index 00000000..e7419c71 --- /dev/null +++ b/zlt-commons/zlt-wechat-common-core/src/main/java/com/central/wechat/feign/fallback/WechatConfigServiceFallbackFactory.java @@ -0,0 +1,38 @@ +package com.central.wechat.feign.fallback; + +import com.central.wechat.entity.WechatConfig; +import com.central.wechat.feign.WechatConfigService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; + +/** + * userService降级工场 + * + * @author zlt + * @date 2019/1/18 + */ +@Slf4j +public class WechatConfigServiceFallbackFactory implements FallbackFactory { + @Override + public WechatConfigService create(Throwable throwable) { + return new WechatConfigService() { + @Override + public WechatConfig getConfig(String type,String tenantId) { + + return new WechatConfig(); + } + + @Override + public WechatConfig getConfigByAppId(String appId) { + return null; + } + + @Override + public WechatConfig getConfigBySerialNumber(String serialNumber) { + return null; + } + + + }; + } +} diff --git a/zlt-commons/zlt-wechat-common-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-wechat-common-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..cc1ba790 --- /dev/null +++ b/zlt-commons/zlt-wechat-common-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1,3 @@ +com.central.wechat.feign.fallback.WechatConfigServiceFallbackFactory + + diff --git a/zlt-commons/zlt-wechat-common-core/src/main/resources/db/migration/V1__create_wechat_config_table.sql b/zlt-commons/zlt-wechat-common-core/src/main/resources/db/migration/V1__create_wechat_config_table.sql new file mode 100644 index 00000000..1c6d18b6 --- /dev/null +++ b/zlt-commons/zlt-wechat-common-core/src/main/resources/db/migration/V1__create_wechat_config_table.sql @@ -0,0 +1,26 @@ +CREATE TABLE `wechat_config` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `type` varchar(10) NOT NULL COMMENT '配置类型:MP-公众号,MINI-小程序,PAY-支付', + `merchant_id` varchar(32) NOT NULL COMMENT '商户ID', + `app_id` varchar(32) NOT NULL COMMENT '应用ID', + `app_secret` varchar(64) NOT NULL COMMENT '应用密钥', + `mch_key` varchar(64) DEFAULT NULL COMMENT '商户API密钥', + `mch_serial_no` varchar(64) DEFAULT NULL COMMENT '商户证书序列号', + `private_key_path` varchar(256) DEFAULT NULL COMMENT '商户私钥文件路径', + `api_v3_key` varchar(64) DEFAULT NULL COMMENT 'APIv3密钥', + `notify_url` varchar(256) DEFAULT NULL COMMENT '支付回调地址', + `token` varchar(64) DEFAULT NULL COMMENT '微信公众号token', + `aes_key` varchar(64) DEFAULT NULL COMMENT '微信公众号aesKey', + `payment_success_template_id` varchar(64) DEFAULT NULL COMMENT '支付成功通知模板ID', + `video_complete_template_id` varchar(64) DEFAULT NULL COMMENT '视频处理完成通知模板ID', + `video_fail_template_id` varchar(64) DEFAULT NULL COMMENT '视频处理失败通知模板ID', + `profit_sharing_enabled` tinyint(1) DEFAULT '1' COMMENT '是否启用分账', + `async_enabled` tinyint(1) DEFAULT '1' COMMENT '是否启用异步处理', + `async_pool_size` int(11) DEFAULT '5' COMMENT '异步处理线程池大小', + `status` tinyint(4) DEFAULT '1' COMMENT '状态:0-禁用,1-启用', + `remark` varchar(256) DEFAULT NULL COMMENT '备注', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_type_merchant` (`type`,`merchant_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信配置表'; \ No newline at end of file diff --git a/zlt-commons/zlt-wechat-spring-boot-starter/pom.xml b/zlt-commons/zlt-wechat-spring-boot-starter/pom.xml new file mode 100644 index 00000000..93bddf5c --- /dev/null +++ b/zlt-commons/zlt-wechat-spring-boot-starter/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + + com.zlt + zlt-commons + 6.0.0 + + + zlt-wechat-spring-boot-starter + 微信Spring Boot启动器 + + + + + com.zlt + zlt-wechat-common-core + ${project.version} + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-autoconfigure + + + \ No newline at end of file diff --git a/zlt-commons/zlt-wechat-spring-boot-starter/src/main/java/com/central/wechat/config/PrivateKeyUtils.java b/zlt-commons/zlt-wechat-spring-boot-starter/src/main/java/com/central/wechat/config/PrivateKeyUtils.java new file mode 100644 index 00000000..a04ff042 --- /dev/null +++ b/zlt-commons/zlt-wechat-spring-boot-starter/src/main/java/com/central/wechat/config/PrivateKeyUtils.java @@ -0,0 +1,77 @@ +package com.central.wechat.config; + +import lombok.extern.slf4j.Slf4j; + +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Base64; + +/** + * 私钥串处理工具类 + * @author lsl + * @date 2025-06-03 + */ +@Slf4j +public class PrivateKeyUtils { + + public static PrivateKey getPrivateKey(String privateKeyStr) { + if (privateKeyStr == null || privateKeyStr.trim().isEmpty()) { + throw new IllegalArgumentException("私钥字符串不能为空"); + } + + // 检查是否是证书而不是私钥 + if (privateKeyStr.contains("-----BEGIN CERTIFICATE-----")) { + throw new IllegalArgumentException("输入的是证书而不是私钥,请提供正确的私钥"); + } + + try { + // 移除所有可能的头部和尾部标记 + String privateKeyPEM = privateKeyStr + .replace("-----BEGIN PRIVATE KEY-----", "") + .replace("-----END PRIVATE KEY-----", "") + // 移除所有空白字符(包括换行符、制表符等) + .replaceAll("\\s+", ""); + + byte[] decoded = Base64.getDecoder().decode(privateKeyPEM); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + return keyFactory.generatePrivate(keySpec); + } catch (IllegalArgumentException e) { + log.error("私钥格式错误: {}", e.getMessage()); + throw new IllegalArgumentException("私钥格式错误: " + e.getMessage(), e); + } catch (Exception e) { + log.error("解析私钥失败,原始私钥字符串: {}", privateKeyStr, e); + throw new RuntimeException("解析私钥失败: " + e.getMessage(), e); + } + } + + public static X509Certificate getCertificate(String certificateStr) { + if (certificateStr == null || certificateStr.trim().isEmpty()) { + throw new IllegalArgumentException("证书字符串不能为空"); + } + + // 检查是否是私钥而不是证书 + if (certificateStr.contains("-----BEGIN PRIVATE KEY-----") || + certificateStr.contains("-----BEGIN RSA PRIVATE KEY-----")) { + throw new IllegalArgumentException("输入的是私钥而不是证书,请提供正确的证书"); + } + + try { + String certificatePEM = certificateStr + .replace("-----BEGIN CERTIFICATE-----", "") + .replace("-----END CERTIFICATE-----", "") + .replaceAll("\\s+", ""); + + byte[] decoded = Base64.getDecoder().decode(certificatePEM); + CertificateFactory factory = CertificateFactory.getInstance("X.509"); + return (X509Certificate) factory.generateCertificate(new java.io.ByteArrayInputStream(decoded)); + } catch (CertificateException e) { + log.error("解析证书失败,原始证书字符串: {}", certificateStr, e); + throw new RuntimeException("解析证书失败: " + e.getMessage(), e); + } + } +} diff --git a/zlt-commons/zlt-wechat-spring-boot-starter/src/main/java/com/central/wechat/config/WechatAutoConfiguration.java b/zlt-commons/zlt-wechat-spring-boot-starter/src/main/java/com/central/wechat/config/WechatAutoConfiguration.java new file mode 100644 index 00000000..2d2d61c5 --- /dev/null +++ b/zlt-commons/zlt-wechat-spring-boot-starter/src/main/java/com/central/wechat/config/WechatAutoConfiguration.java @@ -0,0 +1,75 @@ +package com.central.wechat.config; + +import cn.binarywang.wx.miniapp.api.WxMaService; +import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; +import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; +import com.central.wechat.entity.WechatConfig; +import com.central.wechat.feign.WechatConfigService; +import com.wechat.pay.java.service.payments.jsapi.model.SettleInfo; +import lombok.extern.slf4j.Slf4j; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; +import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Slf4j +@Configuration +@EnableConfigurationProperties(WechatProperties.class) +@AutoConfigureAfter({FeignAutoConfiguration.class, WebMvcAutoConfiguration.class}) +public class WechatAutoConfiguration { + + @Bean + @ConditionalOnBean(WechatConfigService.class) + public WxMpService wxMpService(WechatConfigService configService) { + log.info("WxMpService(公众号相关)被加载,tenantId:{}", getCurrentTenantId()); + WechatConfig wechatConfig = configService.getConfig("MP", getCurrentTenantId()); + WxMpService service = new WxMpServiceImpl(); + WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl(); + + config.setAppId(wechatConfig.getAppId()); + config.setSecret(wechatConfig.getAppSecret()); + + service.setWxMpConfigStorage(config); + return service; + } + + @Bean + @ConditionalOnBean(WechatConfigService.class) + public WxMaService wxMaService(WechatConfigService configService) { + log.info("WxMaService(小程序通知)被加载,tenantId:{}", getCurrentTenantId()); + WechatConfig wechatConfig = configService.getConfig("PAY", getCurrentTenantId()); + WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); + config.setAppid(wechatConfig.getAppId()); + config.setSecret(wechatConfig.getAppSecret()); + WxMaService service = new WxMaServiceImpl(); + service.setWxMaConfig(config); + return service; + } + + + @Bean + @ConditionalOnBean({WechatConfigService.class}) + public WxPayConfigFactory wxPayConfigFactory() { + log.info("WxPayConfigFactory被加载,tenantId:{}", getCurrentTenantId()); + return new WxPayConfigFactory(); + } + + @Bean + @ConditionalOnBean(WechatConfigService.class) + public SettleInfo settleInfo(WechatConfigService configService) { + WechatConfig config = configService.getConfig("PAY", getCurrentTenantId()); + SettleInfo settleInfo = new SettleInfo(); + settleInfo.setProfitSharing(config.getProfitSharingEnabled()); + return settleInfo; + } + + private String getCurrentTenantId() { + return "webApp"; + } +} diff --git a/zlt-commons/zlt-wechat-spring-boot-starter/src/main/java/com/central/wechat/config/WxPayConfigFactory.java b/zlt-commons/zlt-wechat-spring-boot-starter/src/main/java/com/central/wechat/config/WxPayConfigFactory.java new file mode 100644 index 00000000..eeccc4ef --- /dev/null +++ b/zlt-commons/zlt-wechat-spring-boot-starter/src/main/java/com/central/wechat/config/WxPayConfigFactory.java @@ -0,0 +1,147 @@ +package com.central.wechat.config; + +import com.central.wechat.entity.WechatConfig; +import com.central.wechat.feign.WechatConfigService; +import com.wechat.pay.java.core.Config; +import com.wechat.pay.java.core.RSAAutoCertificateConfig; +import com.wechat.pay.java.core.notification.NotificationConfig; +import com.wechat.pay.java.core.notification.NotificationParser; +import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension; +import com.wechat.pay.java.service.profitsharing.ProfitsharingService; +import com.wechat.pay.java.service.refund.RefundService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.stereotype.Component; + +import java.security.PrivateKey; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadPoolExecutor; + +@Slf4j +@Component +public class WxPayConfigFactory { + @Autowired + private WechatConfigService configService; + + // 缓存各个服务的实例 + private final Map configCache = new ConcurrentHashMap<>(); + private final Map jsapiServiceCache = new ConcurrentHashMap<>(); + private final Map notificationParserCache = new ConcurrentHashMap<>(); + private final Map refundServiceCache = new ConcurrentHashMap<>(); + private final Map profitsharingServiceCache = new ConcurrentHashMap<>(); + private final Map executorCache = new ConcurrentHashMap<>(); + + + public Config createConfig(String tenantId) { + return configCache.computeIfAbsent(tenantId, this::buildConfig); + } + + private Config buildConfig(String tenantId) { + log.info("创建微信支付配置,tenantId:{}", tenantId); + WechatConfig config = configService.getConfig("PAY", tenantId); + PrivateKey privateKey = PrivateKeyUtils.getPrivateKey(config.getPrivateKey()); + + return new RSAAutoCertificateConfig.Builder() + .merchantId(config.getMerchantId()) + .privateKey(privateKey) + .merchantSerialNumber(config.getMchSerialNo()) + .apiV3Key(config.getApiV3Key()) + .build(); + } + + public JsapiServiceExtension createJsapiService(String tenantId) { + return jsapiServiceCache.computeIfAbsent(tenantId, this::buildJsapiService); + } + + private JsapiServiceExtension buildJsapiService(String tenantId) { + Config config = createConfig(tenantId); + return new JsapiServiceExtension.Builder().config(config).build(); + } + + public NotificationParser createNotificationParser(String tenantId) { + return notificationParserCache.computeIfAbsent(tenantId, this::buildNotificationParser); + } + + private NotificationParser buildNotificationParser(String tenantId) { + log.info("创建微信支付通知解析器,tenantId:{}", tenantId); + WechatConfig config = configService.getConfig("PAY", tenantId); + PrivateKey privateKey = PrivateKeyUtils.getPrivateKey(config.getPrivateKey()); + + NotificationConfig notificationConfig = new RSAAutoCertificateConfig.Builder() + .merchantId(config.getMerchantId()) + .privateKey(privateKey) + .merchantSerialNumber(config.getMchSerialNo()) + .apiV3Key(config.getApiV3Key()) + .build(); + + return new NotificationParser(notificationConfig); + } + + public RefundService createRefundService(String tenantId) { + return refundServiceCache.computeIfAbsent(tenantId, this::buildRefundService); + } + + private RefundService buildRefundService(String tenantId) { + log.info("创建微信退款服务,tenantId:{}", tenantId); + Config config = createConfig(tenantId); + return new RefundService.Builder().config(config).build(); + } + + public ProfitsharingService createProfitsharingService(String tenantId) { + return profitsharingServiceCache.computeIfAbsent(tenantId, this::buildProfitsharingService); + } + + private ProfitsharingService buildProfitsharingService(String tenantId) { + log.info("创建微信分账服务,tenantId:{}", tenantId); + Config config = createConfig(tenantId); + return new ProfitsharingService.Builder().config(config).build(); + } + + public Executor createExecutor(String tenantId) { + return executorCache.computeIfAbsent(tenantId, this::buildExecutor); + } + + private Executor buildExecutor(String tenantId) { + log.info("创建分账异步执行器,tenantId:{}", tenantId); + WechatConfig config = configService.getConfig("PAY", tenantId); + if (!config.getAsyncEnabled()) { + return null; + } + + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(config.getAsyncPoolSize()); + executor.setMaxPoolSize(config.getAsyncPoolSize()); + executor.setQueueCapacity(100); + executor.setThreadNamePrefix("profit-sharing-" + tenantId + "-"); + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + executor.initialize(); + return executor; + } + + /** + * 清除指定租户的缓存 + */ + public void clearCache(String tenantId) { + configCache.remove(tenantId); + jsapiServiceCache.remove(tenantId); + notificationParserCache.remove(tenantId); + refundServiceCache.remove(tenantId); + profitsharingServiceCache.remove(tenantId); + executorCache.remove(tenantId); + } + + /** + * 清除所有缓存 + */ + public void clearAllCache() { + configCache.clear(); + jsapiServiceCache.clear(); + notificationParserCache.clear(); + refundServiceCache.clear(); + profitsharingServiceCache.clear(); + executorCache.clear(); + } +} diff --git a/zlt-commons/zlt-wechat-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/zlt-commons/zlt-wechat-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..12f6ff0c --- /dev/null +++ b/zlt-commons/zlt-wechat-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +com.central.wechat.config.WechatAutoConfiguration diff --git a/zlt-config/src/main/resources/application-dev.properties b/zlt-config/src/main/resources/application-dev.properties index 80bcb0ac..95919716 100644 --- a/zlt-config/src/main/resources/application-dev.properties +++ b/zlt-config/src/main/resources/application-dev.properties @@ -1,12 +1,17 @@ ########################## 统一变量配置 ########################## ##### 数据库配置 -zlt.datasource.ip=192.168.28.130 +zlt.datasource.ip=127.0.0.1 zlt.datasource.username=root -zlt.datasource.password=1q2w3e4r +zlt.datasource.password=root +#zlt.datasource.ip=sh-cdb-i6yxaaec.sql.tencentcdb.com:58797 +#zlt.datasource.username=root +#zlt.datasource.password=ZXC_zxc!@#123+ ##### redis配置 -spring.data.redis.host=192.168.28.130 +spring.data.redis.host=192.168.2.20 spring.data.redis.port=6379 +spring.data.redis.password=ikingtec123456 +spring.data.redis.database=8 spring.data.redis.timeout=5000 ##### elasticsearch配置 @@ -22,19 +27,58 @@ zlt.fdfs.web-url=192.168.28.130 zlt.fdfs.trackerList=${zlt.fdfs.web-url}:22122 ##### s3配置 -zlt.s3.access-key=minioadmin -zlt.s3.accessKeySecret=minioadmin -zlt.s3.endpoint=http://192.168.28.130:9000 -zlt.s3.bucketName=test +zlt.s3.access-key=cEpebPSIV0t4CIM9TPsl +zlt.s3.accessKeySecret=A5P4kybIlqRMLqWwdgDtNAZJQR6o30Kp7drETf8p +zlt.s3.endpoint=http://81.70.164.178:9000 +zlt.s3.bucketName=gofly +zlt.s3.region=us-east-1 + +zlt.oss.secretId=LTAI5tSNV1RvexXpMMCZhxSe +zlt.oss.secretKey=XocJRWU8emwjjvYLTrc04l91VZMkQK +zlt.oss.endpoint=https://oss-cn-beijing.aliyuncs.com +zlt.oss.bucketName=goflyapp + +#### cos配置 +zlt.cos.secretId=AKIDkMn6B3h7KJ5dIkyzpRr7C6mFUqFWbu1u +zlt.cos.secretKey=jDThssfEZieS4S8bqsgIiAUdbXVVYgdQ +zlt.cos.endpoint=gofly-1333114031.cos.ap-nanjing.myqcloud.com +zlt.cos.bucketName=gofly-1333114031 +zlt.cos.region=ap-nanjing ##### 日志链路追踪 zlt.trace.enable=true -##### 负载均衡隔离(version隔离,只适用于开发环境) +##### 负载均衡隔离(version隔离,只适用于开发环境) zlt.ribbon.isolation.enabled=false -##### mybatis-plus打印完整sql(只适用于开发环境) +##### mybatis-plus打印完整sql(只适用于开发环境) mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl -# 开启版本路由 -#zlt.loadbalance.isolation.enabled=true \ No newline at end of file +# 开启版本路由 +#zlt.loadbalance.isolation.enabled=true + +zlt.security.tencent.appId=wx0c3cc6f1d297644d +zlt.security.tencent.appSecret=9d344e6c86b42105b6e4a018f242e233 +zlt.security.tencent.token=YPbzETU8oe3XguGgwtA4g1DqlFKvw7pT +zlt.security.tencent.encodingAESKey=YPbzETU8oe3XguGgwtA4g1DqlFKvw7pTZiyHTxCiQxh +zlt.security.tencent.templateId=YOUR_TEMPLATE_ID +zlt.security.tencent.jscode2sessionUrl=https://api.weixin.qq.com/sns/jscode2session +zlt.security.tencent.accessTokenUrl=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${zlt.security.tencent.appId}&secret=${zlt.security.tencent.appSecret} +zlt.security.tencent.getwxacodeUrl=https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token= +zlt.security.tencent.pagePath=/pages/link/link?uuid= + + +# 微信支付商户号 +zlt.wxpay.merchantId=1703796518 +# 商户证书序列号 +zlt.wxpay.merchantSerialNumber=11F4AC03C50EB582D3EDE082591D1F9A65388D51 +# 微信支付申请的应用ID +zlt.wxpay.appId=wx30a3c8de94a85584 +# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致) +zlt.wxpay.notifyUrl=https://img.goflytec.com/api-order/wechat/pay/notify +# 微信退款异步通知地址(需外网可访问且与微信支付平台配置一致) +zlt.wxrefund.notifyUrl= https://img.goflytec.com/api-order/wechat/refund/notify +# 商户API私钥路径 +zlt.wxpay.privateKeyPath=D:\\wx\\WXCertUtil\\cert\\1703796518_20250114_cert\\apiclient_key.pem +# 商户APIV3密钥 +zlt.wxpay.apiV3Key=aIt5Vw3cYXSCSd4L5h14kIyDsoXBow7r diff --git a/zlt-config/src/main/resources/application-prod.properties b/zlt-config/src/main/resources/application-prod.properties index 63aa5830..b63bdb52 100644 --- a/zlt-config/src/main/resources/application-prod.properties +++ b/zlt-config/src/main/resources/application-prod.properties @@ -1,18 +1,22 @@ ########################## 统一变量配置 ########################## ##### 数据库配置 -zlt.datasource.ip=192.168.28.130 +zlt.datasource.ip=sh-cdb-i6yxaaec.sql.tencentcdb.com:58797 zlt.datasource.username=root -zlt.datasource.password=1q2w3e4r +zlt.datasource.password=ZXC_zxc!@#123+ ##### redis配置 -spring.data.redis.sentinel.master=mymaster -spring.data.redis.sentinel.nodes=172.17.0.1 -spring.data.redis.password= +spring.data.redis.host=81.70.164.178 +#spring.data.redis.host=127.0.0.1 +spring.data.redis.port=6379 +spring.data.redis.password=mvaiopdle7IwdQrinzTQ +spring.data.redis.database=0 +spring.data.redis.timeout=5000 + ##### elasticsearch配置 -zlt.elasticsearch.uris=192.168.28.130:9200 -zlt.elasticsearch.username= -zlt.elasticsearch.password= +zlt.elasticsearch.uris=119.45.169.13:9200 +zlt.elasticsearch.username=elastic +zlt.elasticsearch.password=iot123456@ ##### sentinel配置 zlt.sentinel.dashboard=192.168.28.130:6999 @@ -22,10 +26,48 @@ zlt.fdfs.web-url=192.168.28.130 zlt.fdfs.trackerList=${zlt.fdfs.web-url}:22122 ##### s3配置 -zlt.s3.access-key=minioadmin -zlt.s3.accessKeySecret=minioadmin -zlt.s3.endpoint=http://192.168.28.130:9000 -zlt.s3.bucketName=test +zlt.s3.access-key=33RdDbIlEFK0z9IJHSqx +zlt.s3.accessKeySecret=mmfSh4gjJm8dck0KaG6fKItpIM3tenWVHS4Ygjlm +zlt.s3.endpoint=http://81.70.164.178:9000 +zlt.s3.bucketName=gofly + +zlt.oss.secretId=LTAI5tSNV1RvexXpMMCZhxSe +zlt.oss.secretKey=XocJRWU8emwjjvYLTrc04l91VZMkQK +zlt.oss.endpoint=https://oss-cn-beijing.aliyuncs.com +zlt.oss.bucketName=goflyapp + +#### cos配置 +zlt.cos.secretId=AKIDkMn6B3h7KJ5dIkyzpRr7C6mFUqFWbu1u +zlt.cos.secretKey=jDThssfEZieS4S8bqsgIiAUdbXVVYgdQ +zlt.cos.endpoint=gofly-1333114031.cos.ap-nanjing.myqcloud.com +zlt.cos.bucketName=gofly-1333114031 +zlt.cos.region=ap-nanjing ##### 日志链路追踪 -zlt.trace.enable=true \ No newline at end of file +zlt.trace.enable=true + +zlt.security.tencent.appId=wx30a3c8de94a85584 +zlt.security.tencent.appSecret=e64d6e3dcfe88d0daee50e77f5a2ee69 +zlt.security.tencent.token=YPbzETU8oe3XguGgwtA4g1DqlFKvw7pT +zlt.security.tencent.encodingAESKey=YPbzETU8oe3XguGgwtA4g1DqlFKvw7pTZiyHTxCiQxh +zlt.security.tencent.templateId=YOUR_TEMPLATE_ID +zlt.security.tencent.jscode2sessionUrl=https://api.weixin.qq.com/sns/jscode2session +zlt.security.tencent.accessTokenUrl=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${zlt.security.tencent.appId}&secret=${zlt.security.tencent.appSecret} +zlt.security.tencent.getwxacodeUrl=https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token= +zlt.security.tencent.pagePath=/pages/link/link?uuid= + +# 微信支付商户号 +zlt.wxpay.merchantId=1703796518 +# 商户证书序列号 +zlt.wxpay.merchantSerialNumber=11F4AC03C50EB582D3EDE082591D1F9A65388D51 +# 61CBFF26EC90204F8F308B6D318E90F14DF233FC +# 微信支付申请的应用ID +zlt.wxpay.appId=wx30a3c8de94a85584 +# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致) +zlt.wxpay.notifyUrl=https://img.goflytec.com/api-order/wechat/pay/notify +# 微信退款异步通知地址(需外网可访问且与微信支付平台配置一致) +zlt.wxrefund.notifyUrl= https://img.goflytec.com/api-order/wechat/refund/notify +# 商户API私钥路径 +zlt.wxpay.privateKeyPath=/data/zlt/cert/apiclient_key.pem +# 商户APIV3密钥 +zlt.wxpay.apiV3Key=aIt5Vw3cYXSCSd4L5h14kIyDsoXBow7r diff --git a/zlt-config/src/main/resources/application-test.properties b/zlt-config/src/main/resources/application-test.properties index 61981671..d7eb3b0e 100644 --- a/zlt-config/src/main/resources/application-test.properties +++ b/zlt-config/src/main/resources/application-test.properties @@ -1,18 +1,22 @@ ########################## 统一变量配置 ########################## ##### 数据库配置 -zlt.datasource.ip=192.168.28.130 +zlt.datasource.ip=127.0.0.1 zlt.datasource.username=root -zlt.datasource.password=1q2w3e4r +zlt.datasource.password=root ##### redis配置 -spring.data.redis.host=192.168.28.130 +spring.data.redis.host=192.168.2.20 spring.data.redis.port=6379 +spring.data.redis.password=ikingtec123456 +spring.data.redis.database=8 spring.data.redis.timeout=5000 + + ##### elasticsearch配置 -zlt.elasticsearch.uris=192.168.28.130:9200 -zlt.elasticsearch.username= -zlt.elasticsearch.password= +zlt.elasticsearch.uris=119.45.169.13:9200 +zlt.elasticsearch.username=elastic +zlt.elasticsearch.password=iot123456@ ##### sentinel配置 zlt.sentinel.dashboard=192.168.28.130:6999 @@ -22,10 +26,43 @@ zlt.fdfs.web-url=192.168.28.130 zlt.fdfs.trackerList=${zlt.fdfs.web-url}:22122 ##### s3配置 -zlt.s3.access-key=minioadmin -zlt.s3.accessKeySecret=minioadmin -zlt.s3.endpoint=http://192.168.28.130:9000 -zlt.s3.bucketName=test +zlt.s3.access-key=33RdDbIlEFK0z9IJHSqx +zlt.s3.accessKeySecret=mmfSh4gjJm8dck0KaG6fKItpIM3tenWVHS4Ygjlm +zlt.s3.endpoint=http://81.70.164.178:9000 +zlt.s3.bucketName=gofly + +zlt.oss.secretId=LTAI5tSNV1RvexXpMMCZhxSe +zlt.oss.secretKey=XocJRWU8emwjjvYLTrc04l91VZMkQK +zlt.oss.endpoint=https://oss-cn-beijing.aliyuncs.com +zlt.oss.bucketName=goflyapp + +#### cos配置 +zlt.cos.secretId=AKIDkMn6B3h7KJ5dIkyzpRr7C6mFUqFWbu1u +zlt.cos.secretKey=jDThssfEZieS4S8bqsgIiAUdbXVVYgdQ +zlt.cos.endpoint=gofly-1333114031.cos.ap-nanjing.myqcloud.com +zlt.cos.bucketName=gofly-1333114031 +zlt.cos.region=ap-nanjing ##### 日志链路追踪 -zlt.trace.enable=true \ No newline at end of file +zlt.trace.enable=true + +zlt.security.tencent.appId=wx30a3c8de94a85584 +zlt.security.tencent.appSecret=e64d6e3dcfe88d0daee50e77f5a2ee69 +zlt.security.tencent.token=YPbzETU8oe3XguGgwtA4g1DqlFKvw7pT +zlt.security.tencent.encodingAESKey=YPbzETU8oe3XguGgwtA4g1DqlFKvw7pTZiyHTxCiQxh +zlt.security.tencent.templateId=YOUR_TEMPLATE_ID +zlt.security.tencent.jscode2sessionUrl=https://api.weixin.qq.com/sns/jscode2session +zlt.security.tencent.accessTokenUrl=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${zlt.security.tencent.appId}&secret=${zlt.security.tencent.appSecret} + +# 微信支付商户号 +zlt.wxpay.merchantId=1703796518 +# 商户证书序列号 +zlt.wxpay.merchantSerialNumber=11F4AC03C50EB582D3EDE082591D1F9A65388D51 +# 微信支付申请的应用ID +zlt.wxpay.appId=wx30a3c8de94a85584 +# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致) +zlt.wxpay.notifyUrl=http://your_domain/weixin/pay/notify +# 商户API私钥路径 +zlt.wxpay.privateKeyPath=D:\\wx\\WXCertUtil\\cert\\1703796518_20250114_cert\\apiclient_key.pem +# 商户APIV3密钥 +zlt.wxpay.apiV3Key=aIt5Vw3cYXSCSd4L5h14kIyDsoXBow7r diff --git a/zlt-config/src/main/resources/bootstrap.properties b/zlt-config/src/main/resources/bootstrap.properties index 6723ea5e..19e3c72f 100644 --- a/zlt-config/src/main/resources/bootstrap.properties +++ b/zlt-config/src/main/resources/bootstrap.properties @@ -1,18 +1,23 @@ ########################## bootstrap级别通用配置 ########################## # 默认开发环境 -spring.profiles.active=dev +spring.profiles.active=prod ##### nacos(注册中心和配置中心)地址 -spring.cloud.nacos.server-addr=192.168.28.130:8848 +spring.cloud.nacos.server-addr=81.70.164.178:8848 +#spring.cloud.nacos.server-addr=127.0.0.1:8848 spring.cloud.nacos.username=nacos -spring.cloud.nacos.password=nacos +#spring.cloud.nacos.password=nacos +spring.cloud.nacos.password=nacosGFLY spring.cloud.nacos.config.file-extension=yml spring.cloud.nacos.config.shared-configs[0].data-id=common.yml spring.cloud.nacos.config.shared-configs[0].refresh=true +spring.cloud.nacos.config.server-addr=${spring.cloud.nacos.server-addr} +spring.cloud.nacos.config.namespace=application + ##### spring-boot-actuator配置 management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always ##### 允许bean覆盖 -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestFilter.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestFilter.java new file mode 100644 index 00000000..bcad0db3 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestFilter.java @@ -0,0 +1,35 @@ +package com.central.gateway.filter; + +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +/** + * 不合法请求过滤器 + * + * @author lsl + * @date 2025/03/11 + * + */ +@Component +public class RequestFilter implements GlobalFilter { + + private boolean isValidMethod(String method) { + // 简单的方法名验证,只允许常见的 HTTP 方法 + return method.matches("^(GET|POST|PUT|DELETE|HEAD|OPTIONS|TRACE)$"); + } + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + ServerHttpRequest httpRequest = exchange.getRequest(); + String method = httpRequest.getMethod().toString(); + if (isValidMethod(method)) { + return chain.filter(exchange); + } else { + return exchange.getResponse().setComplete(); + } + } +} diff --git a/zlt-gateway/sc-gateway/src/main/resources/application.yml b/zlt-gateway/sc-gateway/src/main/resources/application.yml index 541e24bd..fd6a85a7 100644 --- a/zlt-gateway/sc-gateway/src/main/resources/application.yml +++ b/zlt-gateway/sc-gateway/src/main/resources/application.yml @@ -73,6 +73,18 @@ spring: - Path=/api-search/** filters: - StripPrefix=1 + - id: device + uri: lb://device-center + predicates: + - Path=/api-device/** + filters: + - StripPrefix=1 + - id: order + uri: lb://order-center + predicates: + - Path=/api-order/** + filters: + - StripPrefix=1 # sentinel: # datasource.ds1.nacos: # server-addr: ${spring.cloud.nacos.server-addr} @@ -103,6 +115,14 @@ knife4j: service-name: file-center url: /api-file/v3/api-docs/default context-path: /api-file + - name: 设备服务 + service-name: device-center + url: /api-device/v3/api-docs/default + context-path: /api-device + - name: 订单服务 + service-name: order-center + url: /api-order/v3/api-docs/default + context-path: /api-order zlt: security: @@ -117,7 +137,18 @@ zlt: /login.html, /user/login, /oauth/authorize, /api-uaa/tokens/key, - /*/v3/api-docs/** + /*/v3/api-docs/**, + /api-order/files/path, + /api-order/update, + /api-order/queue/first, + /api-order/wechat/**, + /api-order/home/carousel/app, + /api-order/device/status, + /api-order/token/callback, + /api-device/stream-urls, + /api-device/token/query, + /api-order/user/temp, + /api-file/file/expires auth: urlPermission: #是否开启url级别权限 @@ -147,4 +178,4 @@ hystrix: execution: isolation: thread: - timeoutInMilliseconds: 1000 \ No newline at end of file + timeoutInMilliseconds: 1000 diff --git a/zlt-monitor/log-center/src/main/java/com/central/log/controller/SysLogController.java b/zlt-monitor/log-center/src/main/java/com/central/log/controller/SysLogController.java index 6869e882..14be7c7d 100644 --- a/zlt-monitor/log-center/src/main/java/com/central/log/controller/SysLogController.java +++ b/zlt-monitor/log-center/src/main/java/com/central/log/controller/SysLogController.java @@ -12,7 +12,8 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; -import java.util.*; +import java.util.ArrayList; +import java.util.List; /** * 系统日志 @@ -50,6 +51,6 @@ public class SysLogController { } else { logList = new ArrayList<>(0); } - return PageResult.builder().data(logList).code(0).count((long) logList.size()).build(); + return PageResult.builder().data(logList).resp_code(0).count((long) logList.size()).build(); } } diff --git a/zlt-register/nacos/LICENSE b/zlt-register/nacos/LICENSE deleted file mode 100644 index 5be5ed21..00000000 --- a/zlt-register/nacos/LICENSE +++ /dev/null @@ -1,316 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (properties) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ------- -This product has a bundle logback, which is available under the EPL v1.0 License. -The source code of logback can be found at https://github.com/qos-ch/logback. - -Logback LICENSE ---------------- - -Logback: the reliable, generic, fast and flexible logging framework. -Copyright (C) 1999-2015, QOS.ch. All rights reserved. - -This program and the accompanying materials are dual-licensed under -either the terms of the Eclipse Public License v1.0 as published by -the Eclipse Foundation - - or (per the licensee's choosing) - -under the terms of the GNU Lesser General Public License version 2.1 -as published by the Free Software Foundation. - ------- -This product has a bundle slf4j, which is available under the MIT License. -The source code of slf4j can be found at https://github.com/qos-ch/slf4j. - - Copyright (c) 2004-2017 QOS.ch - All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ------- -This product has a bundle javassist, which is available under the ASL2 License. -The source code of javassist can be found at https://github.com/jboss-javassist/javassist. - - Copyright (C) 1999- by Shigeru Chiba, All rights reserved. - - Javassist (JAVA programming ASSISTant) makes Java bytecode manipulation simple. - It is a class library for editing bytecodes in Java; it enables Java programs to define a new class - at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, - Javassist provides two levels of API: source level and bytecode level. If the users use the source- level API, - they can edit a class file without knowledge of the specifications of the Java bytecode. - The whole API is designed with only the vocabulary of the Java language. - You can even specify inserted bytecode in the form of source text; Javassist compiles it on the fly. - On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors. - - This software is distributed under the Mozilla Public License Version 1.1, - the GNU Lesser General Public License Version 2.1 or later, or the Apache License Version 2.0. - ------- -This product has a bundle jna, which is available under the ASL2 License. -The source code of jna can be found at https://github.com/java-native-access/jna. - - This copy of JNA is licensed under the - Apache (Software) License, version 2.0 ("the License"). - See the License for details about distribution rights, and the - specific rights regarding derivate works. - - You may obtain a copy of the License at: - - http://www.apache.org/licenses/ - - A copy is also included in the downloadable source code package - containing JNA, in file "AL2.0", under the same directory - as this file. ------- -This product has a bundle guava, which is available under the ASL2 License. -The source code of guava can be found at https://github.com/google/guava. - - Copyright (C) 2007 The Guava authors - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ------- -This product has a bundle OpenMessaging, which is available under the ASL2 License. -The source code of OpenMessaging can be found at https://github.com/openmessaging/openmessaging. - - Copyright (C) 2017 The OpenMessaging authors. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/zlt-register/nacos/NOTICE b/zlt-register/nacos/NOTICE deleted file mode 100644 index 3a2af572..00000000 --- a/zlt-register/nacos/NOTICE +++ /dev/null @@ -1,36 +0,0 @@ -Nacos -Copyright 2018-2019 The Apache Software Foundation - -This product includes software developed at -The Alibaba MiddleWare Group. - ------- -This product has a bundle netty: - The Spring oot Project - ================= - -Please visit the Netty web site for more information: - - * http://netty.io/ - -Copyright 2014 The Netty Project - -The Netty Project licenses this file to you under the Apache License, -version 2.0 (the "License"); you may not use this file except in compliance -with the License. You may obtain a copy of the License at: - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -License for the specific language governing permissions and limitations -under the License. - -Also, please refer to each LICENSE..txt file, which is located in -the 'license' directory of the distribution file, for the license terms of the -components that this product depends on. - ------- -This product has a bundle commons-lang, which includes software from the Spring Framework, -under the Apache License 2.0 (see: StringUtils.containsWhitespace()) \ No newline at end of file diff --git a/zlt-register/nacos/bin/shutdown.cmd b/zlt-register/nacos/bin/shutdown.cmd deleted file mode 100644 index e3ae899e..00000000 --- a/zlt-register/nacos/bin/shutdown.cmd +++ /dev/null @@ -1,24 +0,0 @@ -@echo off -rem Copyright 1999-2018 Alibaba Group Holding Ltd. -rem Licensed under the Apache License, Version 2.0 (the "License"); -rem you may not use this file except in compliance with the License. -rem You may obtain a copy of the License at -rem -rem http://www.apache.org/licenses/LICENSE-2.0 -rem -rem Unless required by applicable law or agreed to in writing, software -rem distributed under the License is distributed on an "AS IS" BASIS, -rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -rem See the License for the specific language governing permissions and -rem limitations under the License. -if not exist "%JAVA_HOME%\bin\jps.exe" echo Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better! & EXIT /B 1 - -setlocal - -set "PATH=%JAVA_HOME%\bin;%PATH%" - -echo killing nacos server - -for /f "tokens=1" %%i in ('jps -m ^| find "nacos.nacos"') do ( taskkill /F /PID %%i ) - -echo Done! diff --git a/zlt-register/nacos/bin/shutdown.sh b/zlt-register/nacos/bin/shutdown.sh deleted file mode 100644 index e3e14fed..00000000 --- a/zlt-register/nacos/bin/shutdown.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash - -# Copyright 1999-2018 Alibaba Group Holding Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at - -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -cd `dirname $0`/../target -target_dir=`pwd` - -pid=`ps ax | grep -i 'nacos.nacos' | grep ${target_dir} | grep java | grep -v grep | awk '{print $1}'` -if [ -z "$pid" ] ; then - echo "No nacosServer running." - exit -1; -fi - -echo "The nacosServer(${pid}) is running..." - -kill ${pid} - -echo "Send shutdown request to nacosServer(${pid}) OK" diff --git a/zlt-register/nacos/bin/startup.cmd b/zlt-register/nacos/bin/startup.cmd deleted file mode 100644 index c9910877..00000000 --- a/zlt-register/nacos/bin/startup.cmd +++ /dev/null @@ -1,95 +0,0 @@ -@echo off -rem Copyright 1999-2018 Alibaba Group Holding Ltd. -rem Licensed under the Apache License, Version 2.0 (the "License"); -rem you may not use this file except in compliance with the License. -rem You may obtain a copy of the License at -rem -rem http://www.apache.org/licenses/LICENSE-2.0 -rem -rem Unless required by applicable law or agreed to in writing, software -rem distributed under the License is distributed on an "AS IS" BASIS, -rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -rem See the License for the specific language governing permissions and -rem limitations under the License. -if not exist "%JAVA_HOME%\bin\java.exe" echo Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better! & EXIT /B 1 -set "JAVA=%JAVA_HOME%\bin\java.exe" - -setlocal enabledelayedexpansion - -set BASE_DIR=%~dp0 -rem added double quotation marks to avoid the issue caused by the folder names containing spaces. -rem removed the last 5 chars(which means \bin\) to get the base DIR. -set BASE_DIR="%BASE_DIR:~0,-5%" - -set CUSTOM_SEARCH_LOCATIONS=file:%BASE_DIR%/conf/ - -set MODE="cluster" -set FUNCTION_MODE="all" -set SERVER=nacos-server -set MODE_INDEX=-1 -set FUNCTION_MODE_INDEX=-1 -set SERVER_INDEX=-1 -set EMBEDDED_STORAGE_INDEX=-1 -set EMBEDDED_STORAGE="" - - -set i=0 -for %%a in (%*) do ( - if "%%a" == "-m" ( set /a MODE_INDEX=!i!+1 ) - if "%%a" == "-f" ( set /a FUNCTION_MODE_INDEX=!i!+1 ) - if "%%a" == "-s" ( set /a SERVER_INDEX=!i!+1 ) - if "%%a" == "-p" ( set /a EMBEDDED_STORAGE_INDEX=!i!+1 ) - set /a i+=1 -) - -set i=0 -for %%a in (%*) do ( - if %MODE_INDEX% == !i! ( set MODE="%%a" ) - if %FUNCTION_MODE_INDEX% == !i! ( set FUNCTION_MODE="%%a" ) - if %SERVER_INDEX% == !i! (set SERVER="%%a") - if %EMBEDDED_STORAGE_INDEX% == !i! (set EMBEDDED_STORAGE="%%a") - set /a i+=1 -) - -rem if nacos startup mode is standalone -if %MODE% == "standalone" ( - echo "nacos is starting with standalone" - set "NACOS_OPTS=-Dnacos.standalone=true" - set "NACOS_JVM_OPTS=-Xms512m -Xmx512m -Xmn256m" -) - -rem if nacos startup mode is cluster -if %MODE% == "cluster" ( - echo "nacos is starting with cluster" - if %EMBEDDED_STORAGE% == "embedded" ( - set "NACOS_OPTS=-DembeddedStorage=true" - ) - - set "NACOS_JVM_OPTS=-server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m -XX:-OmitStackTraceInFastThrow -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=%BASE_DIR%\logs\java_heapdump.hprof -XX:-UseLargePages" -) - -rem set nacos's functionMode -if %FUNCTION_MODE% == "config" ( - set "NACOS_OPTS=%NACOS_OPTS% -Dnacos.functionMode=config" -) - -if %FUNCTION_MODE% == "naming" ( - set "NACOS_OPTS=%NACOS_OPTS% -Dnacos.functionMode=naming" -) - -rem set nacos options -set "NACOS_OPTS=%NACOS_OPTS% -Dloader.path=%BASE_DIR%/plugins/health,%BASE_DIR%/plugins/cmdb" -set "NACOS_OPTS=%NACOS_OPTS% -Dnacos.home=%BASE_DIR%" -set "NACOS_OPTS=%NACOS_OPTS% -jar %BASE_DIR%\target\%SERVER%.jar" - -rem set nacos spring config location -set "NACOS_CONFIG_OPTS=--spring.config.additional-location=%CUSTOM_SEARCH_LOCATIONS%" - -rem set nacos log4j file location -set "NACOS_LOG4J_OPTS=--logging.config=%BASE_DIR%/conf/nacos-logback.xml" - - -set COMMAND="%JAVA%" %NACOS_JVM_OPTS% %NACOS_OPTS% %NACOS_CONFIG_OPTS% %NACOS_LOG4J_OPTS% nacos.nacos %* - -rem start nacos command -%COMMAND% diff --git a/zlt-register/nacos/bin/startup.sh b/zlt-register/nacos/bin/startup.sh deleted file mode 100644 index f16c5e6c..00000000 --- a/zlt-register/nacos/bin/startup.sh +++ /dev/null @@ -1,142 +0,0 @@ -#!/bin/bash - -# Copyright 1999-2018 Alibaba Group Holding Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at - -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -cygwin=false -darwin=false -os400=false -case "`uname`" in -CYGWIN*) cygwin=true;; -Darwin*) darwin=true;; -OS400*) os400=true;; -esac -error_exit () -{ - echo "ERROR: $1 !!" - exit 1 -} -[ ! -e "$JAVA_HOME/bin/java" ] && JAVA_HOME=$HOME/jdk/java -[ ! -e "$JAVA_HOME/bin/java" ] && JAVA_HOME=/usr/java -[ ! -e "$JAVA_HOME/bin/java" ] && JAVA_HOME=/opt/taobao/java -[ ! -e "$JAVA_HOME/bin/java" ] && unset JAVA_HOME - -if [ -z "$JAVA_HOME" ]; then - if $darwin; then - - if [ -x '/usr/libexec/java_home' ] ; then - export JAVA_HOME=`/usr/libexec/java_home` - - elif [ -d "/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home" ]; then - export JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home" - fi - else - JAVA_PATH=`dirname $(readlink -f $(which javac))` - if [ "x$JAVA_PATH" != "x" ]; then - export JAVA_HOME=`dirname $JAVA_PATH 2>/dev/null` - fi - fi - if [ -z "$JAVA_HOME" ]; then - error_exit "Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better!" - fi -fi - -export SERVER="nacos-server" -export MODE="cluster" -export FUNCTION_MODE="all" -export MEMBER_LIST="" -export EMBEDDED_STORAGE="" -while getopts ":m:f:s:c:p:" opt -do - case $opt in - m) - MODE=$OPTARG;; - f) - FUNCTION_MODE=$OPTARG;; - s) - SERVER=$OPTARG;; - c) - MEMBER_LIST=$OPTARG;; - p) - EMBEDDED_STORAGE=$OPTARG;; - ?) - echo "Unknown parameter" - exit 1;; - esac -done - -export JAVA_HOME -export JAVA="$JAVA_HOME/bin/java" -export BASE_DIR=`cd $(dirname $0)/..; pwd` -export CUSTOM_SEARCH_LOCATIONS=file:${BASE_DIR}/conf/ - -#=========================================================================================== -# JVM Configuration -#=========================================================================================== -if [[ "${MODE}" == "standalone" ]]; then - JAVA_OPT="${JAVA_OPT} -Xms512m -Xmx512m -Xmn256m" - JAVA_OPT="${JAVA_OPT} -Dnacos.standalone=true" -else - if [[ "${EMBEDDED_STORAGE}" == "embedded" ]]; then - JAVA_OPT="${JAVA_OPT} -DembeddedStorage=true" - fi - JAVA_OPT="${JAVA_OPT} -server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m" - JAVA_OPT="${JAVA_OPT} -XX:-OmitStackTraceInFastThrow -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${BASE_DIR}/logs/java_heapdump.hprof" - JAVA_OPT="${JAVA_OPT} -XX:-UseLargePages" - -fi - -if [[ "${FUNCTION_MODE}" == "config" ]]; then - JAVA_OPT="${JAVA_OPT} -Dnacos.functionMode=config" -elif [[ "${FUNCTION_MODE}" == "naming" ]]; then - JAVA_OPT="${JAVA_OPT} -Dnacos.functionMode=naming" -fi - -JAVA_OPT="${JAVA_OPT} -Dnacos.member.list=${MEMBER_LIST}" - -JAVA_MAJOR_VERSION=$($JAVA -version 2>&1 | sed -E -n 's/.* version "([0-9]*).*$/\1/p') -if [[ "$JAVA_MAJOR_VERSION" -ge "9" ]] ; then - JAVA_OPT="${JAVA_OPT} -Xlog:gc*:file=${BASE_DIR}/logs/nacos_gc.log:time,tags:filecount=10,filesize=102400" -else - JAVA_OPT="${JAVA_OPT} -Djava.ext.dirs=${JAVA_HOME}/jre/lib/ext:${JAVA_HOME}/lib/ext" - JAVA_OPT="${JAVA_OPT} -Xloggc:${BASE_DIR}/logs/nacos_gc.log -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M" -fi - -JAVA_OPT="${JAVA_OPT} -Dloader.path=${BASE_DIR}/plugins/health,${BASE_DIR}/plugins/cmdb" -JAVA_OPT="${JAVA_OPT} -Dnacos.home=${BASE_DIR}" -JAVA_OPT="${JAVA_OPT} -jar ${BASE_DIR}/target/${SERVER}.jar" -JAVA_OPT="${JAVA_OPT} ${JAVA_OPT_EXT}" -JAVA_OPT="${JAVA_OPT} --spring.config.additional-location=${CUSTOM_SEARCH_LOCATIONS}" -JAVA_OPT="${JAVA_OPT} --logging.config=${BASE_DIR}/conf/nacos-logback.xml" -JAVA_OPT="${JAVA_OPT} --server.max-http-header-size=524288" - -if [ ! -d "${BASE_DIR}/logs" ]; then - mkdir ${BASE_DIR}/logs -fi - -echo "$JAVA ${JAVA_OPT}" - -if [[ "${MODE}" == "standalone" ]]; then - echo "nacos is starting with standalone" -else - echo "nacos is starting with cluster" -fi - -# check the start.out log output file -if [ ! -f "${BASE_DIR}/logs/start.out" ]; then - touch "${BASE_DIR}/logs/start.out" -fi -# start -echo "$JAVA ${JAVA_OPT}" > ${BASE_DIR}/logs/start.out 2>&1 & -nohup $JAVA ${JAVA_OPT} nacos.nacos >> ${BASE_DIR}/logs/start.out 2>&1 & -echo "nacos is starting,you can check the ${BASE_DIR}/logs/start.out" diff --git a/zlt-register/nacos/conf/1.4.0-ipv6_support-update.sql b/zlt-register/nacos/conf/1.4.0-ipv6_support-update.sql deleted file mode 100644 index f480147a..00000000 --- a/zlt-register/nacos/conf/1.4.0-ipv6_support-update.sql +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -ALTER TABLE `config_info_tag` -MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`; - -ALTER TABLE `his_config_info` -MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL AFTER `src_user`; - -ALTER TABLE `config_info` -MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`; - -ALTER TABLE `config_info_beta` -MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`; \ No newline at end of file diff --git a/zlt-register/nacos/conf/application.properties b/zlt-register/nacos/conf/application.properties deleted file mode 100644 index 3f84c38f..00000000 --- a/zlt-register/nacos/conf/application.properties +++ /dev/null @@ -1,201 +0,0 @@ -# -# Copyright 1999-2018 Alibaba Group Holding Ltd. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -#*************** Spring Boot Related Configurations ***************# -### Default web context path: -server.servlet.contextPath=/nacos -### Default web server port: -server.port=8848 - -#*************** Network Related Configurations ***************# -### If prefer hostname over ip for Nacos server addresses in cluster.conf: -# nacos.inetutils.prefer-hostname-over-ip=false - -### Specify local server's IP: -# nacos.inetutils.ip-address= - - -#*************** Config Module Related Configurations ***************# -### If use MySQL as datasource: -# spring.datasource.platform=mysql - -### Count of DB: -# db.num=1 - -### Connect URL of DB: -# db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC -# db.user.0=nacos -# db.password.0=nacos - -### Connection pool configuration: hikariCP -db.pool.config.connectionTimeout=30000 -db.pool.config.validationTimeout=10000 -db.pool.config.maximumPoolSize=20 -db.pool.config.minimumIdle=2 - -#*************** Naming Module Related Configurations ***************# -### Data dispatch task execution period in milliseconds: -# nacos.naming.distro.taskDispatchPeriod=200 - -### Data count of batch sync task: -# nacos.naming.distro.batchSyncKeyCount=1000 - -### Retry delay in milliseconds if sync task failed: -# nacos.naming.distro.syncRetryDelay=5000 - -### If enable data warmup. If set to false, the server would accept request without local data preparation: -# nacos.naming.data.warmup=true - -### If enable the instance auto expiration, kind like of health check of instance: -# nacos.naming.expireInstance=true - -nacos.naming.empty-service.auto-clean=true -nacos.naming.empty-service.clean.initial-delay-ms=50000 -nacos.naming.empty-service.clean.period-time-ms=30000 - -### Add in 2.0.0 -### The interval to clean empty service -# nacos.naming.clean.empty-service.interval=60000 - -### The expired time to clean empty service -# nacos.naming.clean.empty-service.expired-time=60000 - -### The interval to clean expired metadata -# nacos.naming.clean.expired-metadata.interval=5000 - -### The expired time to clean metadata -# nacos.naming.clean.expired-metadata.expired-time=60000 - -#*************** CMDB Module Related Configurations ***************# -### The interval to dump external CMDB in seconds: -# nacos.cmdb.dumpTaskInterval=3600 - -### The interval of polling data change event in seconds: -# nacos.cmdb.eventTaskInterval=10 - -### The interval of loading labels in seconds: -# nacos.cmdb.labelTaskInterval=300 - -### If turn on data loading task: -# nacos.cmdb.loadDataAtStart=false - - -#*************** Metrics Related Configurations ***************# -### Metrics for prometheus -#management.endpoints.web.exposure.include=* - -### Metrics for elastic search -management.metrics.export.elastic.enabled=false -#management.metrics.export.elastic.host=http://localhost:9200 - -### Metrics for influx -management.metrics.export.influx.enabled=false -#management.metrics.export.influx.db=springboot -#management.metrics.export.influx.uri=http://localhost:8086 -#management.metrics.export.influx.auto-create-db=true -#management.metrics.export.influx.consistency=one -#management.metrics.export.influx.compressed=true - - -#*************** Access Log Related Configurations ***************# -### If turn on the access log: -server.tomcat.accesslog.enabled=true - -### The access log pattern: -server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i - -### The directory of access log: -server.tomcat.basedir= - - -#*************** Access Control Related Configurations ***************# -### If enable spring security, this option is deprecated in 1.2.0: -#spring.security.enabled=false - -### The ignore urls of auth, is deprecated in 1.2.0: -nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/** - -### The auth system to use, currently only 'nacos' is supported: -nacos.core.auth.system.type=nacos - -### If turn on auth system: -nacos.core.auth.enabled=false - -### The token expiration in seconds: -nacos.core.auth.default.token.expire.seconds=18000 - -### The default token: -nacos.core.auth.default.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789 - -### Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay. -nacos.core.auth.caching.enabled=true - -### Since 1.4.1, Turn on/off white auth for user-agent: nacos-server, only for upgrade from old version. -nacos.core.auth.enable.userAgentAuthWhite=true - -### Since 1.4.1, worked when nacos.core.auth.enabled=true and nacos.core.auth.enable.userAgentAuthWhite=false. -### The two properties is the white list for auth and used by identity the request from other server. -nacos.core.auth.server.identity.key= -nacos.core.auth.server.identity.value= - -#*************** Istio Related Configurations ***************# -### If turn on the MCP server: -nacos.istio.mcp.server.enabled=false - - - -###*************** Add from 1.3.0 ***************### - - -#*************** Core Related Configurations ***************# - -### set the WorkerID manually -# nacos.core.snowflake.worker-id= - -### Member-MetaData -# nacos.core.member.meta.site= -# nacos.core.member.meta.adweight= -# nacos.core.member.meta.weight= - -### MemberLookup -### Addressing pattern category, If set, the priority is highest -# nacos.core.member.lookup.type=[file,address-server] -## Set the cluster list with a configuration file or command-line argument -# nacos.member.list=192.168.16.101:8847?raft_port=8807,192.168.16.101?raft_port=8808,192.168.16.101:8849?raft_port=8809 -## for AddressServerMemberLookup -# Maximum number of retries to query the address server upon initialization -# nacos.core.address-server.retry=5 -## Server domain name address of [address-server] mode -# address.server.domain=jmenv.tbsite.net -## Server port of [address-server] mode -# address.server.port=8080 -## Request address of [address-server] mode -# address.server.url=/nacos/serverlist - -#*************** JRaft Related Configurations ***************# - -### Sets the Raft cluster election timeout, default value is 5 second -# nacos.core.protocol.raft.data.election_timeout_ms=5000 -### Sets the amount of time the Raft snapshot will execute periodically, default is 30 minute -# nacos.core.protocol.raft.data.snapshot_interval_secs=30 -### raft internal worker threads -# nacos.core.protocol.raft.data.core_thread_num=8 -### Number of threads required for raft business request processing -# nacos.core.protocol.raft.data.cli_service_thread_num=4 -### raft linear read strategy. Safe linear reads are used by default, that is, the Leader tenure is confirmed by heartbeat -# nacos.core.protocol.raft.data.read_index_type=ReadOnlySafe -### rpc request timeout, default 5 seconds -# nacos.core.protocol.raft.data.rpc_request_timeout_ms=5000 diff --git a/zlt-register/nacos/conf/application.properties.example b/zlt-register/nacos/conf/application.properties.example deleted file mode 100644 index 8e171829..00000000 --- a/zlt-register/nacos/conf/application.properties.example +++ /dev/null @@ -1,177 +0,0 @@ -# -# Copyright 1999-2018 Alibaba Group Holding Ltd. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -#*************** Spring Boot Related Configurations ***************# -### Default web context path: -server.servlet.contextPath=/nacos -### Default web server port: -server.port=8848 - -#*************** Network Related Configurations ***************# -### If prefer hostname over ip for Nacos server addresses in cluster.conf: -# nacos.inetutils.prefer-hostname-over-ip=false - -### Specify local server's IP: -# nacos.inetutils.ip-address= - - -#*************** Config Module Related Configurations ***************# -### If use MySQL as datasource: -# spring.datasource.platform=mysql - -### Count of DB: -# db.num=1 - -### Connect URL of DB: -# db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC -# db.user.0=nacos -# db.password.0=nacos - - -#*************** Naming Module Related Configurations ***************# -### Data dispatch task execution period in milliseconds: -# nacos.naming.distro.taskDispatchPeriod=200 - -### Data count of batch sync task: -# nacos.naming.distro.batchSyncKeyCount=1000 - -### Retry delay in milliseconds if sync task failed: -# nacos.naming.distro.syncRetryDelay=5000 - -### If enable data warmup. If set to false, the server would accept request without local data preparation: -# nacos.naming.data.warmup=true - -### If enable the instance auto expiration, kind like of health check of instance: -# nacos.naming.expireInstance=true - -nacos.naming.empty-service.auto-clean=true -nacos.naming.empty-service.clean.initial-delay-ms=50000 -nacos.naming.empty-service.clean.period-time-ms=30000 - - -#*************** CMDB Module Related Configurations ***************# -### The interval to dump external CMDB in seconds: -# nacos.cmdb.dumpTaskInterval=3600 - -### The interval of polling data change event in seconds: -# nacos.cmdb.eventTaskInterval=10 - -### The interval of loading labels in seconds: -# nacos.cmdb.labelTaskInterval=300 - -### If turn on data loading task: -# nacos.cmdb.loadDataAtStart=false - - -#*************** Metrics Related Configurations ***************# -### Metrics for prometheus -#management.endpoints.web.exposure.include=* - -### Metrics for elastic search -management.metrics.export.elastic.enabled=false -#management.metrics.export.elastic.host=http://localhost:9200 - -### Metrics for influx -management.metrics.export.influx.enabled=false -#management.metrics.export.influx.db=springboot -#management.metrics.export.influx.uri=http://localhost:8086 -#management.metrics.export.influx.auto-create-db=true -#management.metrics.export.influx.consistency=one -#management.metrics.export.influx.compressed=true - - -#*************** Access Log Related Configurations ***************# -### If turn on the access log: -server.tomcat.accesslog.enabled=true - -### The access log pattern: -server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i - -### The directory of access log: -server.tomcat.basedir= - - -#*************** Access Control Related Configurations ***************# -### If enable spring security, this option is deprecated in 1.2.0: -#spring.security.enabled=false - -### The ignore urls of auth, is deprecated in 1.2.0: -nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/** - -### The auth system to use, currently only 'nacos' is supported: -nacos.core.auth.system.type=nacos - -### If turn on auth system: -nacos.core.auth.enabled=false - -### The token expiration in seconds: -nacos.core.auth.default.token.expire.seconds=18000 - -### The default token: -nacos.core.auth.default.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789 - -### Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay. -nacos.core.auth.caching.enabled=true - - -#*************** Istio Related Configurations ***************# -### If turn on the MCP server: -nacos.istio.mcp.server.enabled=false - - - -###*************** Add from 1.3.0 ***************### - - -#*************** Core Related Configurations ***************# - -### set the WorkerID manually -# nacos.core.snowflake.worker-id= - -### Member-MetaData -# nacos.core.member.meta.site= -# nacos.core.member.meta.adweight= -# nacos.core.member.meta.weight= - -### MemberLookup -### Addressing pattern category, If set, the priority is highest -# nacos.core.member.lookup.type=[file,address-server] -## Set the cluster list with a configuration file or command-line argument -# nacos.member.list=192.168.16.101:8847?raft_port=8807,192.168.16.101?raft_port=8808,192.168.16.101:8849?raft_port=8809 -## for AddressServerMemberLookup -# Maximum number of retries to query the address server upon initialization -# nacos.core.address-server.retry=5 -## Server domain name address of [address-server] mode -# address.server.domain=jmenv.tbsite.net -## Server port of [address-server] mode -# address.server.port=8080 -## Request address of [address-server] mode -# address.server.url=/nacos/serverlist - -#*************** JRaft Related Configurations ***************# - -### Sets the Raft cluster election timeout, default value is 5 second -# nacos.core.protocol.raft.data.election_timeout_ms=5000 -### Sets the amount of time the Raft snapshot will execute periodically, default is 30 minute -# nacos.core.protocol.raft.data.snapshot_interval_secs=30 -### raft internal worker threads -# nacos.core.protocol.raft.data.core_thread_num=8 -### Number of threads required for raft business request processing -# nacos.core.protocol.raft.data.cli_service_thread_num=4 -### raft linear read strategy. Safe linear reads are used by default, that is, the Leader tenure is confirmed by heartbeat -# nacos.core.protocol.raft.data.read_index_type=ReadOnlySafe -### rpc request timeout, default 5 seconds -# nacos.core.protocol.raft.data.rpc_request_timeout_ms=5000 diff --git a/zlt-register/nacos/conf/cluster.conf.example b/zlt-register/nacos/conf/cluster.conf.example deleted file mode 100644 index 0e3a7214..00000000 --- a/zlt-register/nacos/conf/cluster.conf.example +++ /dev/null @@ -1,21 +0,0 @@ -# -# Copyright 1999-2018 Alibaba Group Holding Ltd. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -#it is ip -#example -192.168.16.101:8847 -192.168.16.102 -192.168.16.103 diff --git a/zlt-register/nacos/conf/nacos-logback.xml b/zlt-register/nacos/conf/nacos-logback.xml deleted file mode 100644 index 15f7623a..00000000 --- a/zlt-register/nacos/conf/nacos-logback.xml +++ /dev/null @@ -1,778 +0,0 @@ - - - - - - - - - - ${nacos.home}/logs/cmdb-main.log - true - - ${nacos.home}/logs/cmdb-main.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/naming-server.log - true - - ${LOG_HOME}/naming-server.log.%d{yyyy-MM-dd}.%i - 1GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - 0 - 1024 - true - - - - - ${LOG_HOME}/naming-raft.log - true - - ${LOG_HOME}/naming-raft.log.%d{yyyy-MM-dd}.%i - 1GB - 7 - 3GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - 0 - 1024 - true - - - - - - ${LOG_HOME}/naming-distro.log - true - - ${LOG_HOME}/naming-distro.log.%d{yyyy-MM-dd}.%i - 1GB - 7 - 3GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - 0 - 1024 - true - - - - - ${LOG_HOME}/naming-event.log - true - - ${LOG_HOME}/naming-event.log.%d{yyyy-MM-dd}.%i - 1GB - 7 - 3GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - 0 - 1024 - true - - - - - ${LOG_HOME}/naming-push.log - true - - ${LOG_HOME}/naming-push.log.%d{yyyy-MM-dd}.%i - 1GB - 7 - 3GB - true - - - %date %level %msg%n%n - UTF-8 - - - - ${LOG_HOME}/naming-rt.log - true - - ${LOG_HOME}/naming-rt.log.%d{yyyy-MM-dd}.%i - 1GB - 7 - 3GB - true - - - %msg%n - UTF-8 - - - - - ${LOG_HOME}/naming-performance.log - true - - ${LOG_HOME}/naming-performance.log.%d{yyyy-MM-dd}.%i - 1GB - 7 - 3GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - - ${LOG_HOME}/config-dump.log - true - - ${LOG_HOME}/config-dump.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - ${LOG_HOME}/config-pull.log - true - - ${LOG_HOME}/config-pull.log.%d{yyyy-MM-dd}.%i - 20MB - 7 - 128MB - true - - - %date %level %msg%n%n - UTF-8 - - - - ${LOG_HOME}/config-fatal.log - true - - ${LOG_HOME}/config-fatal.log.%d{yyyy-MM-dd}.%i - 20MB - 7 - 128MB - true - - - %date %level %msg%n%n - UTF-8 - - - - ${LOG_HOME}/config-memory.log - true - - ${LOG_HOME}/config-memory.log.%d{yyyy-MM-dd}.%i - 20MB - 7 - 128MB - true - - - %date %level %msg%n%n - UTF-8 - - - - ${LOG_HOME}/config-pull-check.log - true - - ${LOG_HOME}/config-pull-check.log.%d{yyyy-MM-dd}.%i - 1GB - 7 - 3GB - true - - - %msg%n - UTF-8 - - - - - ${LOG_HOME}/config-client-request.log - true - - ${LOG_HOME}/config-client-request.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date|%msg%n - UTF-8 - - - - - ${LOG_HOME}/config-trace.log - true - - ${LOG_HOME}/config-trace.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date|%msg%n - UTF-8 - - - - - ${LOG_HOME}/config-notify.log - true - - ${LOG_HOME}/config-notify.log.%d{yyyy-MM-dd}.%i - 1GB - 7 - 3GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/config-server.log - true - - ${LOG_HOME}/config-server.log.%d{yyyy-MM-dd}.%i - 50MB - 7 - 512MB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/nacos.log - true - - ${LOG_HOME}/nacos.log.%d{yyyy-MM-dd}.%i - 50MB - 7 - 512MB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/nacos-address.log - true - - ${LOG_HOME}/nacos-address.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/istio-main.log - true - - ${LOG_HOME}/istio-main.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/core-auth.log - true - - ${LOG_HOME}/core-auth.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/protocol-raft.log - true - - ${LOG_HOME}/protocol-raft.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/protocol-distro.log - true - - ${LOG_HOME}/protocol-distro.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/nacos-cluster.log - true - - ${LOG_HOME}/nacos-cluster.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/alipay-jraft.log - true - - ${LOG_HOME}/alipay-jraft.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - - - ${LOG_HOME}/tps-control.log - true - - ${LOG_HOME}/tps-control.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/tps-control-digest.log - true - - ${LOG_HOME}/tps-control-digest.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/tps-control-detail.log - true - - ${LOG_HOME}/tps-control-detail.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - - ${LOG_HOME}/remote.log - true - - ${LOG_HOME}/remote.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/remote-digest.log - true - - ${LOG_HOME}/remote-digest.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - ${LOG_HOME}/remote-push.log - true - - ${LOG_HOME}/remote-push.log.%d{yyyy-MM-dd}.%i - 2GB - 7 - 7GB - true - - - %date %level %msg%n%n - UTF-8 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/zlt-register/nacos/conf/nacos-mysql.sql b/zlt-register/nacos/conf/nacos-mysql.sql deleted file mode 100644 index 551d6598..00000000 --- a/zlt-register/nacos/conf/nacos-mysql.sql +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/******************************************/ -/* 数据库全名 = nacos_config */ -/* 表名称 = config_info */ -/******************************************/ -CREATE TABLE `config_info` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', - `data_id` varchar(255) NOT NULL COMMENT 'data_id', - `group_id` varchar(255) DEFAULT NULL, - `content` longtext NOT NULL COMMENT 'content', - `md5` varchar(32) DEFAULT NULL COMMENT 'md5', - `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间', - `src_user` text COMMENT 'source user', - `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip', - `app_name` varchar(128) DEFAULT NULL, - `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段', - `c_desc` varchar(256) DEFAULT NULL, - `c_use` varchar(64) DEFAULT NULL, - `effect` varchar(64) DEFAULT NULL, - `type` varchar(64) DEFAULT NULL, - `c_schema` text, - PRIMARY KEY (`id`), - UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info'; - -/******************************************/ -/* 数据库全名 = nacos_config */ -/* 表名称 = config_info_aggr */ -/******************************************/ -CREATE TABLE `config_info_aggr` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', - `data_id` varchar(255) NOT NULL COMMENT 'data_id', - `group_id` varchar(255) NOT NULL COMMENT 'group_id', - `datum_id` varchar(255) NOT NULL COMMENT 'datum_id', - `content` longtext NOT NULL COMMENT '内容', - `gmt_modified` datetime NOT NULL COMMENT '修改时间', - `app_name` varchar(128) DEFAULT NULL, - `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段', - PRIMARY KEY (`id`), - UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段'; - - -/******************************************/ -/* 数据库全名 = nacos_config */ -/* 表名称 = config_info_beta */ -/******************************************/ -CREATE TABLE `config_info_beta` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', - `data_id` varchar(255) NOT NULL COMMENT 'data_id', - `group_id` varchar(128) NOT NULL COMMENT 'group_id', - `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name', - `content` longtext NOT NULL COMMENT 'content', - `beta_ips` varchar(1024) DEFAULT NULL COMMENT 'betaIps', - `md5` varchar(32) DEFAULT NULL COMMENT 'md5', - `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间', - `src_user` text COMMENT 'source user', - `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip', - `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段', - PRIMARY KEY (`id`), - UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta'; - -/******************************************/ -/* 数据库全名 = nacos_config */ -/* 表名称 = config_info_tag */ -/******************************************/ -CREATE TABLE `config_info_tag` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', - `data_id` varchar(255) NOT NULL COMMENT 'data_id', - `group_id` varchar(128) NOT NULL COMMENT 'group_id', - `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id', - `tag_id` varchar(128) NOT NULL COMMENT 'tag_id', - `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name', - `content` longtext NOT NULL COMMENT 'content', - `md5` varchar(32) DEFAULT NULL COMMENT 'md5', - `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间', - `src_user` text COMMENT 'source user', - `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip', - PRIMARY KEY (`id`), - UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag'; - -/******************************************/ -/* 数据库全名 = nacos_config */ -/* 表名称 = config_tags_relation */ -/******************************************/ -CREATE TABLE `config_tags_relation` ( - `id` bigint(20) NOT NULL COMMENT 'id', - `tag_name` varchar(128) NOT NULL COMMENT 'tag_name', - `tag_type` varchar(64) DEFAULT NULL COMMENT 'tag_type', - `data_id` varchar(255) NOT NULL COMMENT 'data_id', - `group_id` varchar(128) NOT NULL COMMENT 'group_id', - `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id', - `nid` bigint(20) NOT NULL AUTO_INCREMENT, - PRIMARY KEY (`nid`), - UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`), - KEY `idx_tenant_id` (`tenant_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation'; - -/******************************************/ -/* 数据库全名 = nacos_config */ -/* 表名称 = group_capacity */ -/******************************************/ -CREATE TABLE `group_capacity` ( - `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `group_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群', - `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值', - `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量', - `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值', - `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数,,0表示使用默认值', - `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值', - `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量', - `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间', - PRIMARY KEY (`id`), - UNIQUE KEY `uk_group_id` (`group_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表'; - -/******************************************/ -/* 数据库全名 = nacos_config */ -/* 表名称 = his_config_info */ -/******************************************/ -CREATE TABLE `his_config_info` ( - `id` bigint(64) unsigned NOT NULL, - `nid` bigint(20) unsigned NOT NULL AUTO_INCREMENT, - `data_id` varchar(255) NOT NULL, - `group_id` varchar(128) NOT NULL, - `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name', - `content` longtext NOT NULL, - `md5` varchar(32) DEFAULT NULL, - `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `src_user` text, - `src_ip` varchar(50) DEFAULT NULL, - `op_type` char(10) DEFAULT NULL, - `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段', - PRIMARY KEY (`nid`), - KEY `idx_gmt_create` (`gmt_create`), - KEY `idx_gmt_modified` (`gmt_modified`), - KEY `idx_did` (`data_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造'; - - -/******************************************/ -/* 数据库全名 = nacos_config */ -/* 表名称 = tenant_capacity */ -/******************************************/ -CREATE TABLE `tenant_capacity` ( - `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `tenant_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID', - `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值', - `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量', - `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值', - `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数', - `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值', - `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量', - `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间', - PRIMARY KEY (`id`), - UNIQUE KEY `uk_tenant_id` (`tenant_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表'; - - -CREATE TABLE `tenant_info` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', - `kp` varchar(128) NOT NULL COMMENT 'kp', - `tenant_id` varchar(128) default '' COMMENT 'tenant_id', - `tenant_name` varchar(128) default '' COMMENT 'tenant_name', - `tenant_desc` varchar(256) DEFAULT NULL COMMENT 'tenant_desc', - `create_source` varchar(32) DEFAULT NULL COMMENT 'create_source', - `gmt_create` bigint(20) NOT NULL COMMENT '创建时间', - `gmt_modified` bigint(20) NOT NULL COMMENT '修改时间', - PRIMARY KEY (`id`), - UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`), - KEY `idx_tenant_id` (`tenant_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info'; - -CREATE TABLE `users` ( - `username` varchar(50) NOT NULL PRIMARY KEY, - `password` varchar(500) NOT NULL, - `enabled` boolean NOT NULL -); - -CREATE TABLE `roles` ( - `username` varchar(50) NOT NULL, - `role` varchar(50) NOT NULL, - UNIQUE INDEX `idx_user_role` (`username` ASC, `role` ASC) USING BTREE -); - -CREATE TABLE `permissions` ( - `role` varchar(50) NOT NULL, - `resource` varchar(255) NOT NULL, - `action` varchar(8) NOT NULL, - UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE -); - -INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE); - -INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN'); diff --git a/zlt-register/nacos/conf/schema.sql b/zlt-register/nacos/conf/schema.sql deleted file mode 100644 index dfa8d754..00000000 --- a/zlt-register/nacos/conf/schema.sql +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -CREATE SCHEMA nacos AUTHORIZATION nacos; - -CREATE TABLE config_info ( - id bigint NOT NULL generated by default as identity, - data_id varchar(255) NOT NULL, - group_id varchar(128) NOT NULL, - tenant_id varchar(128) default '', - app_name varchar(128), - content CLOB, - md5 varchar(32) DEFAULT NULL, - gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', - gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', - src_user varchar(128) DEFAULT NULL, - src_ip varchar(50) DEFAULT NULL, - c_desc varchar(256) DEFAULT NULL, - c_use varchar(64) DEFAULT NULL, - effect varchar(64) DEFAULT NULL, - type varchar(64) DEFAULT NULL, - c_schema LONG VARCHAR DEFAULT NULL, - constraint configinfo_id_key PRIMARY KEY (id), - constraint uk_configinfo_datagrouptenant UNIQUE (data_id,group_id,tenant_id)); - -CREATE INDEX configinfo_dataid_key_idx ON config_info(data_id); -CREATE INDEX configinfo_groupid_key_idx ON config_info(group_id); -CREATE INDEX configinfo_dataid_group_key_idx ON config_info(data_id, group_id); - -CREATE TABLE his_config_info ( - id bigint NOT NULL, - nid bigint NOT NULL generated by default as identity, - data_id varchar(255) NOT NULL, - group_id varchar(128) NOT NULL, - tenant_id varchar(128) default '', - app_name varchar(128), - content CLOB, - md5 varchar(32) DEFAULT NULL, - gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00.000', - gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00.000', - src_user varchar(128), - src_ip varchar(50) DEFAULT NULL, - op_type char(10) DEFAULT NULL, - constraint hisconfiginfo_nid_key PRIMARY KEY (nid)); - -CREATE INDEX hisconfiginfo_dataid_key_idx ON his_config_info(data_id); -CREATE INDEX hisconfiginfo_gmt_create_idx ON his_config_info(gmt_create); -CREATE INDEX hisconfiginfo_gmt_modified_idx ON his_config_info(gmt_modified); - - -CREATE TABLE config_info_beta ( - id bigint NOT NULL generated by default as identity, - data_id varchar(255) NOT NULL, - group_id varchar(128) NOT NULL, - tenant_id varchar(128) default '', - app_name varchar(128), - content CLOB, - beta_ips varchar(1024), - md5 varchar(32) DEFAULT NULL, - gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', - gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', - src_user varchar(128), - src_ip varchar(50) DEFAULT NULL, - constraint configinfobeta_id_key PRIMARY KEY (id), - constraint uk_configinfobeta_datagrouptenant UNIQUE (data_id,group_id,tenant_id)); - -CREATE TABLE config_info_tag ( - id bigint NOT NULL generated by default as identity, - data_id varchar(255) NOT NULL, - group_id varchar(128) NOT NULL, - tenant_id varchar(128) default '', - tag_id varchar(128) NOT NULL, - app_name varchar(128), - content CLOB, - md5 varchar(32) DEFAULT NULL, - gmt_create timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', - gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', - src_user varchar(128), - src_ip varchar(50) DEFAULT NULL, - constraint configinfotag_id_key PRIMARY KEY (id), - constraint uk_configinfotag_datagrouptenanttag UNIQUE (data_id,group_id,tenant_id,tag_id)); - -CREATE TABLE config_info_aggr ( - id bigint NOT NULL generated by default as identity, - data_id varchar(255) NOT NULL, - group_id varchar(128) NOT NULL, - tenant_id varchar(128) default '', - datum_id varchar(255) NOT NULL, - app_name varchar(128), - content CLOB, - gmt_modified timestamp NOT NULL DEFAULT '2010-05-05 00:00:00', - constraint configinfoaggr_id_key PRIMARY KEY (id), - constraint uk_configinfoaggr_datagrouptenantdatum UNIQUE (data_id,group_id,tenant_id,datum_id)); - -CREATE TABLE app_list ( - id bigint NOT NULL generated by default as identity, - app_name varchar(128) NOT NULL, - is_dynamic_collect_disabled smallint DEFAULT 0, - last_sub_info_collected_time timestamp DEFAULT '1970-01-01 08:00:00.0', - sub_info_lock_owner varchar(128), - sub_info_lock_time timestamp DEFAULT '1970-01-01 08:00:00.0', - constraint applist_id_key PRIMARY KEY (id), - constraint uk_appname UNIQUE (app_name)); - -CREATE TABLE app_configdata_relation_subs ( - id bigint NOT NULL generated by default as identity, - app_name varchar(128) NOT NULL, - data_id varchar(255) NOT NULL, - group_id varchar(128) NOT NULL, - gmt_modified timestamp DEFAULT '2010-05-05 00:00:00', - constraint configdatarelationsubs_id_key PRIMARY KEY (id), - constraint uk_app_sub_config_datagroup UNIQUE (app_name, data_id, group_id)); - - -CREATE TABLE app_configdata_relation_pubs ( - id bigint NOT NULL generated by default as identity, - app_name varchar(128) NOT NULL, - data_id varchar(255) NOT NULL, - group_id varchar(128) NOT NULL, - gmt_modified timestamp DEFAULT '2010-05-05 00:00:00', - constraint configdatarelationpubs_id_key PRIMARY KEY (id), - constraint uk_app_pub_config_datagroup UNIQUE (app_name, data_id, group_id)); - -CREATE TABLE config_tags_relation ( - id bigint NOT NULL, - tag_name varchar(128) NOT NULL, - tag_type varchar(64) DEFAULT NULL, - data_id varchar(255) NOT NULL, - group_id varchar(128) NOT NULL, - tenant_id varchar(128) DEFAULT '', - nid bigint NOT NULL generated by default as identity, - constraint config_tags_id_key PRIMARY KEY (nid), - constraint uk_configtagrelation_configidtag UNIQUE (id, tag_name, tag_type)); - -CREATE INDEX config_tags_tenant_id_idx ON config_tags_relation(tenant_id); - -CREATE TABLE group_capacity ( - id bigint NOT NULL generated by default as identity, - group_id varchar(128) DEFAULT '', - quota int DEFAULT 0, - usage int DEFAULT 0, - max_size int DEFAULT 0, - max_aggr_count int DEFAULT 0, - max_aggr_size int DEFAULT 0, - max_history_count int DEFAULT 0, - gmt_create timestamp DEFAULT '2010-05-05 00:00:00', - gmt_modified timestamp DEFAULT '2010-05-05 00:00:00', - constraint group_capacity_id_key PRIMARY KEY (id), - constraint uk_group_id UNIQUE (group_id)); - -CREATE TABLE tenant_capacity ( - id bigint NOT NULL generated by default as identity, - tenant_id varchar(128) DEFAULT '', - quota int DEFAULT 0, - usage int DEFAULT 0, - max_size int DEFAULT 0, - max_aggr_count int DEFAULT 0, - max_aggr_size int DEFAULT 0, - max_history_count int DEFAULT 0, - gmt_create timestamp DEFAULT '2010-05-05 00:00:00', - gmt_modified timestamp DEFAULT '2010-05-05 00:00:00', - constraint tenant_capacity_id_key PRIMARY KEY (id), - constraint uk_tenant_id UNIQUE (tenant_id)); - -CREATE TABLE tenant_info ( - id bigint NOT NULL generated by default as identity, - kp varchar(128) NOT NULL, - tenant_id varchar(128) DEFAULT '', - tenant_name varchar(128) DEFAULT '', - tenant_desc varchar(256) DEFAULT NULL, - create_source varchar(32) DEFAULT NULL, - gmt_create bigint NOT NULL, - gmt_modified bigint NOT NULL, - constraint tenant_info_id_key PRIMARY KEY (id), - constraint uk_tenant_info_kptenantid UNIQUE (kp,tenant_id)); -CREATE INDEX tenant_info_tenant_id_idx ON tenant_info(tenant_id); - -CREATE TABLE users ( - username varchar(50) NOT NULL PRIMARY KEY, - password varchar(500) NOT NULL, - enabled boolean NOT NULL DEFAULT true -); - -CREATE TABLE roles ( - username varchar(50) NOT NULL, - role varchar(50) NOT NULL, - constraint uk_username_role UNIQUE (username,role) -); - -CREATE TABLE permissions ( - role varchar(50) NOT NULL, - resource varchar(512) NOT NULL, - action varchar(8) NOT NULL, - constraint uk_role_permission UNIQUE (role,resource,action) -); - -INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE); - -INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN'); - - -/******************************************/ -/* ipv6 support */ -/******************************************/ -ALTER TABLE `config_info_tag` -MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`; - -ALTER TABLE `his_config_info` -MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL AFTER `src_user`; - -ALTER TABLE `config_info` -MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`; - -ALTER TABLE `config_info_beta` -MODIFY COLUMN `src_ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT 'source ip' AFTER `src_user`; \ No newline at end of file diff --git a/zlt-register/nacos/target/nacos-server.jar b/zlt-register/nacos/target/nacos-server.jar deleted file mode 100644 index dfb57b71..00000000 Binary files a/zlt-register/nacos/target/nacos-server.jar and /dev/null differ diff --git a/zlt-uaa/pom.xml b/zlt-uaa/pom.xml index 6c01eaf0..dbf6a1f6 100644 --- a/zlt-uaa/pom.xml +++ b/zlt-uaa/pom.xml @@ -46,6 +46,11 @@ zlt-redis-spring-boot-starter + + com.zlt + zlt-wechat-common-core + + com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery @@ -92,6 +97,7 @@ org.apache.tomcat.embed tomcat-embed-core + @@ -135,4 +141,4 @@ ${project.artifactId} - \ No newline at end of file + diff --git a/zlt-uaa/src/main/java/com/central/UaaServerApp.java b/zlt-uaa/src/main/java/com/central/UaaServerApp.java index 04738baf..117a24d5 100644 --- a/zlt-uaa/src/main/java/com/central/UaaServerApp.java +++ b/zlt-uaa/src/main/java/com/central/UaaServerApp.java @@ -7,10 +7,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; -/** +/** * @author zlt */ -@EnableFeignClients +@EnableFeignClients(basePackages = {"com.central"}) @MapperScan(basePackages = "com.central.oauth.mapper") @EnableFeignInterceptor @EnableDiscoveryClient diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java index 51c98439..e71fbd5f 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java +++ b/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java @@ -14,6 +14,8 @@ import com.central.oauth.support.password.PasswordAuthenticationConverter; import com.central.oauth.support.password.PasswordAuthenticationProvider; import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationConverter; import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationProvider; +import com.central.oauth.support.tencent.TencentAuthenticationConverter; +import com.central.oauth.support.tencent.TencentAuthenticationProvider; import com.central.oauth2.common.component.CustomAuthorizationServiceIntrospector; import com.central.oauth2.common.component.CustomBearerTokenResolver; import com.central.oauth2.common.config.BaseSecurityConfig; @@ -72,7 +74,6 @@ public class AuthorizationServerConfig { private final RegisteredClientService registeredClientService; private final RedisSecurityContextRepository securityContextRepository; private final AuthenticationSuccessHandler authenticationSuccessHandler; - /** * spring security 默认的安全策略 */ @@ -108,6 +109,7 @@ public class AuthorizationServerConfig { .authenticationProvider(new PasswordCodeAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder, validateCodeService)) .authenticationProvider(new OpenIdAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory)) .authenticationProvider(new MobileAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder)) + .authenticationProvider(new TencentAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory,securityProperties)) ) // 开启OpenID Connect 1.0协议相关端点 .oidc(Customizer.withDefaults()) @@ -146,6 +148,7 @@ public class AuthorizationServerConfig { new PasswordAuthenticationConverter(), new PasswordCodeAuthenticationConverter(), new OpenIdAuthenticationConverter(), - new MobileAuthenticationConverter())); + new MobileAuthenticationConverter(), + new TencentAuthenticationConverter())); } } diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java index a3148273..602bff38 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java @@ -1,5 +1,6 @@ package com.central.oauth.service; +import com.central.wechat.entity.WechatConfig; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; @@ -31,4 +32,17 @@ public interface ZltUserDetailsService extends UserDetailsService { * @param userId 用户id/openId */ UserDetails loadUserByUserId(String userId) throws UsernameNotFoundException; + + /** + * 根据微信用户id/openId查询用户 + * @param wxOpenId 用户id/openId + */ + UserDetails loadUserByWxOpenId(String wxOpenId,String mobile,String unionId) throws UsernameNotFoundException; + + /** + * 根据appId获取APP + * @param appId + * @return + */ + WechatConfig loadMiniAppConfig(String appId); } diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java index aaf43e81..4ba7a8e9 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java @@ -58,7 +58,7 @@ public class ClientServiceImpl extends SuperServiceImpl im } List list = baseMapper.findList(page, params); page.setRecords(list); - return PageResult.builder().data(list).code(0).count(page.getTotal()).build(); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); } @Override diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java index 5877d0d2..3d936c33 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java @@ -4,7 +4,6 @@ import cn.hutool.core.util.PageUtil; import cn.hutool.core.util.StrUtil; import com.central.common.constant.SecurityConstants; import com.central.common.model.PageResult; -import com.central.common.redis.template.RedisRepository; import com.central.oauth.model.TokenVo; import com.central.oauth.service.ITokensService; import lombok.RequiredArgsConstructor; @@ -14,14 +13,11 @@ import org.redisson.api.RBucket; import org.redisson.api.RList; import org.redisson.api.RedissonClient; import org.redisson.codec.SerializationCodec; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.stereotype.Service; -import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -79,7 +75,7 @@ public class RedisTokensServiceImpl implements ITokensService { result.add(tokenVo); } } - return PageResult.builder().data(result).code(0).count(size).build(); + return PageResult.builder().data(result).resp_code(0).count(size).build(); } /** diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RegisteredClientService.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RegisteredClientService.java index 857765b2..d43eb0d7 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RegisteredClientService.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RegisteredClientService.java @@ -37,7 +37,7 @@ public class RegisteredClientService { public PageResult listClient(Map params, boolean isPage) { PageResult clientPage = clientService.listClient(params, isPage); PageResult result = new PageResult<>(); - result.setCode(clientPage.getCode()); + result.setResp_code(clientPage.getResp_code()); result.setCount(clientPage.getCount()); result.setData(BeanUtil.copyToList(clientPage.getData(), ClientDto.class)); return result; diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java index 51159368..1044d172 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java @@ -5,10 +5,13 @@ import com.central.common.feign.UserService; import com.central.common.model.SysUser; import com.central.common.utils.LoginUserUtils; import com.central.oauth.service.ZltUserDetailsService; +import com.central.wechat.entity.WechatConfig; +import com.central.wechat.feign.WechatConfigService; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -27,6 +30,9 @@ public class UserDetailServiceImpl implements ZltUserDetailsService { @Resource private UserService userService; + @Resource + private WechatConfigService wechatConfigService; + @Override public boolean supports(String accountType) { return ACCOUNT_TYPE.equals(accountType); @@ -49,6 +55,18 @@ public class UserDetailServiceImpl implements ZltUserDetailsService { return LoginUserUtils.getLoginAppUser(sysUser); } + @Override + public UserDetails loadUserByWxOpenId(String wxOpenId,String mobile,String unionId) throws UsernameNotFoundException { + SysUser sysUser = userService.findByWxOpenId(wxOpenId,mobile,unionId); + checkUser(sysUser); + return LoginUserUtils.getLoginAppUser(sysUser); + } + + @Override + public WechatConfig loadMiniAppConfig(String appId) { + return wechatConfigService.getConfigByAppId(appId); + } + @Override public UserDetails loadUserByMobile(String mobile) { SysUser sysUser = userService.findByMobile(mobile); diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationConverter.java b/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationConverter.java new file mode 100644 index 00000000..b7c096aa --- /dev/null +++ b/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationConverter.java @@ -0,0 +1,48 @@ +package com.central.oauth.support.tencent; + +import com.central.oauth.support.base.BaseAuthenticationConverter; +import com.central.oauth.utils.OAuthEndpointUtils; +import com.central.oauth2.common.token.BaseAuthenticationToken; +import com.central.oauth2.common.token.TencentAuthenticationToken; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.util.MultiValueMap; + +import java.util.List; + +/** + * @author: lsl + * @date: 2024/12/18 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +public class TencentAuthenticationConverter extends BaseAuthenticationConverter { + + private String appCode = "wx30a3c8de94a85584"; + + @Override + protected String supportGrantType() { + return TencentAuthenticationToken.GRANT_TYPE.getValue(); + } + + @Override + protected List paramNames() { + return List.of(OAuth2ParameterNames.CODE); + } + + @Override + protected BaseAuthenticationToken getToken(MultiValueMap parameters) { + String code = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.CODE); + String encryptedData = OAuthEndpointUtils.getParam(parameters,"encryptedData"); + String iv = OAuthEndpointUtils.getParam(parameters,"iv"); + //如果参数缺省,默认使用平台提供的APPID + if (parameters.containsKey("appCode")) { + appCode = OAuthEndpointUtils.getParam(parameters,"appCode"); + } + + return new TencentAuthenticationToken(code, encryptedData, iv, appCode); + } + + + +} diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationProvider.java new file mode 100644 index 00000000..02b64ca8 --- /dev/null +++ b/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationProvider.java @@ -0,0 +1,179 @@ +package com.central.oauth.support.tencent; + +import com.alibaba.fastjson.JSONObject; +import com.central.oauth.exception.CustomOAuth2AuthenticationException; +import com.central.oauth.service.impl.UserDetailServiceFactory; +import com.central.oauth.support.base.BaseAuthenticationProvider; +import com.central.oauth2.common.properties.SecurityProperties; +import com.central.oauth2.common.token.TencentAuthenticationToken; +import com.central.wechat.entity.WechatConfig; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.core.OAuth2Token; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; +import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator; +import org.springframework.util.Assert; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.util.Base64; +import java.util.Map; + +/** + * 微信小程序登录 provider + * + * @author lsl + * @version 1.0 + * @date 2024/12/16 + *

+ * Blog: http://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Slf4j +@Setter +@Getter +public class TencentAuthenticationProvider extends BaseAuthenticationProvider { + private final UserDetailServiceFactory userDetailsServiceFactory; + private final SecurityProperties securityProperties; + + public TencentAuthenticationProvider(OAuth2AuthorizationService authorizationService + , OAuth2TokenGenerator tokenGenerator + , UserDetailServiceFactory userDetailsServiceFactory + , SecurityProperties securityProperties ) { + super(authorizationService, tokenGenerator); + Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null"); + this.userDetailsServiceFactory = userDetailsServiceFactory; + this.securityProperties = securityProperties; + } + + @Override + public boolean supports(Class authentication) { + return TencentAuthenticationToken.class.isAssignableFrom(authentication); + } + + @Override + protected Authentication getPrincipal(Authentication authentication) { + TencentAuthenticationToken authToken = (TencentAuthenticationToken) authentication; + + String code = (String) authToken.getPrincipal(); + String encryptedData = authToken.getEncryptedData(); + String iv = authToken.getIv(); + String appCode = authToken.getAppCode(); // 前端需传递 + + // 1. 根据appid查找配置 + WechatConfig config = userDetailsServiceFactory.getService(authToken).loadMiniAppConfig(appCode); + if (config == null) { + throw new CustomOAuth2AuthenticationException("不支持的appid"); + } + + // 2. 用查到的appid/secret调用微信接口 + Map wxLoginResult = getWxSessionResult(code, config.getAppId(), config.getAppSecret()); + + UserDetails userDetails; + try { + String openId = wxLoginResult.get("openid").toString(); + String sessionKey = wxLoginResult.get("session_key").toString(); + log.info("openId:{},sessionKey:{},res:{}", openId, sessionKey,wxLoginResult); + String unionId = MapUtils.getString(wxLoginResult, "unionid"); + String mobile = decryptPhoneNumber(encryptedData,sessionKey,iv); + userDetails = userDetailsServiceFactory.getService(authToken).loadUserByWxOpenId(openId,mobile, unionId); + + } catch (AuthenticationException e) { + throw new CustomOAuth2AuthenticationException(e.getMessage()); + } + if (userDetails == null) { + + throw new CustomOAuth2AuthenticationException("用户登录信息待处理,请重新登录"); + } + return new TencentAuthenticationToken(userDetails, userDetails.getAuthorities(),encryptedData, iv,appCode); + } + + @Override + protected AuthorizationGrantType grantType() { + return TencentAuthenticationToken.GRANT_TYPE; + } + + /** + * 微信小程序第三方登录,或微信APP安全登录 + * + * @param code 小程序code + * @return + */ + private Map getWxSessionResult(String code, String appid, String secret) { + + if (code == null || code.isEmpty()) { + throw new CustomOAuth2AuthenticationException("Code cannot be null or empty"); + } + + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap params = new LinkedMultiValueMap<>(); + params.add("appid", appid); + params.add("secret", secret); + params.add("js_code", code); + params.add("grant_type", "authorization_code"); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED); + + HttpEntity> requestEntity = new HttpEntity<>(params, headers); + + ResponseEntity responseEntity = restTemplate.exchange(securityProperties.getTencent().getJscode2sessionUrl(), HttpMethod.POST, requestEntity, String.class); + + if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody().contains("openid")) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + return objectMapper.readValue(responseEntity.getBody(), Map.class); + } catch (Exception e) { + throw new CustomOAuth2AuthenticationException("Failed obtain wxOpenid:"+ e.getMessage()); + } + }else { + throw new CustomOAuth2AuthenticationException("Failed obtain wxOpenid"); + } + } + + /** + * 解析手机号 + * @param encryptedData + * @param sessionKey + * @param iv + * @return + */ + public String decryptPhoneNumber(String encryptedData, String sessionKey, String iv) { + try { + // Base64解码 + byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData); + byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey); + byte[] ivBytes = Base64.getDecoder().decode(iv); + + // AES解密 + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES"); + IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); + cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); + byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes); + + // 解析解密后的数据 + String decryptedData = new String(decryptedBytes, "UTF-8"); + JSONObject jsonObject = JSONObject.parseObject(decryptedData); + return jsonObject.getString("purePhoneNumber"); // 获取手机号 + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/zlt-uaa/src/main/resources/application.yml b/zlt-uaa/src/main/resources/application.yml index 1b33a10e..d4d77a7e 100644 --- a/zlt-uaa/src/main/resources/application.yml +++ b/zlt-uaa/src/main/resources/application.yml @@ -1,6 +1,7 @@ spring: datasource: - url: jdbc:mysql://${zlt.datasource.ip}:3306/oauth-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai +# url: jdbc:mysql://${zlt.datasource.ip}:3306/oauth-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + url: jdbc:mysql://${zlt.datasource.ip}/oauth-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: ${zlt.datasource.username} password: ${zlt.datasource.password} driver-class-name: com.mysql.cj.jdbc.Driver @@ -44,4 +45,8 @@ zlt: enabled: false includeSqls: # 应用列表 - - com.central.oauth.mapper.ClientMapper.findList \ No newline at end of file + - com.central.oauth.mapper.ClientMapper.findList +uaa: + wx: + # 平台默认的APPID + appId: wx0c3cc6f1d297644d diff --git a/zlt-uaa/src/main/resources/bootstrap.yml b/zlt-uaa/src/main/resources/bootstrap.yml index a21c53e0..aff9b849 100644 --- a/zlt-uaa/src/main/resources/bootstrap.yml +++ b/zlt-uaa/src/main/resources/bootstrap.yml @@ -8,9 +8,13 @@ server: spring: application: name: uaa-server + cloud: + nacos: + discovery: + ip: 124.222.128.40 encrypt: key-store: location: classpath:zlt.jks secret: zlt!@#$ - alias: zlt \ No newline at end of file + alias: zlt diff --git a/zlt-web/layui-web/src/main/resources/static/login.html b/zlt-web/layui-web/src/main/resources/static/login.html index 59807664..5b3505ee 100644 --- a/zlt-web/layui-web/src/main/resources/static/login.html +++ b/zlt-web/layui-web/src/main/resources/static/login.html @@ -96,7 +96,7 @@ success: function (data) { //console.log(JSON.stringify(data)); if (data.resp_code === 0) { - config.putToken(data.datas); + config.putToken(data.data); layer.msg('登录成功', {icon: 1, time: 500}, function () { location.replace('./'); }); @@ -126,4 +126,4 @@ }); - \ No newline at end of file + diff --git a/zlt-web/layui-web/src/main/resources/static/module/apiUrl.js b/zlt-web/layui-web/src/main/resources/static/module/apiUrl.js index db75a8fd..b90a3c3c 100644 --- a/zlt-web/layui-web/src/main/resources/static/module/apiUrl.js +++ b/zlt-web/layui-web/src/main/resources/static/module/apiUrl.js @@ -1 +1 @@ -var my_api_server_url = 'http://127.0.0.1:9900/'; \ No newline at end of file +var my_api_server_url = 'http://127.0.0.1:9900/'; diff --git a/zlt-web/layui-web/src/main/resources/static/module/index.js b/zlt-web/layui-web/src/main/resources/static/module/index.js index 183a5f3c..5b2e28bd 100644 --- a/zlt-web/layui-web/src/main/resources/static/module/index.js +++ b/zlt-web/layui-web/src/main/resources/static/module/index.js @@ -33,7 +33,7 @@ layui.define(['config', 'admin', 'layer', 'laytpl', 'element', 'form'], function var laytpl = layui.laytpl; var element = layui.element; var form = layui.form; - + var index = { // 渲染左侧菜单栏 initLeftNav: function () { @@ -191,7 +191,7 @@ layui.define(['config', 'admin', 'layer', 'laytpl', 'element', 'form'], function admin.req('api-user/users/current', {}, function (data) { layer.closeAll('loading'); if (data && data.resp_code === 0) { - let user = data.datas; + let user = data.data; config.putUser(user); admin.putTempData("permissions",user.permissions); success(user); diff --git a/zlt-web/layui-web/src/main/resources/static/pages/device/index.html b/zlt-web/layui-web/src/main/resources/static/pages/device/index.html new file mode 100644 index 00000000..a999f852 --- /dev/null +++ b/zlt-web/layui-web/src/main/resources/static/pages/device/index.html @@ -0,0 +1,52 @@ +

+
+

Wayline file information

+ +
首页 + Wayline file information + +
+ + +
+
+ 搜索: +   + + +
+ + +
+
+
+ + + \ No newline at end of file diff --git a/zlt-web/layui-web/src/main/resources/static/pages/search/index_manager_view.html b/zlt-web/layui-web/src/main/resources/static/pages/search/index_manager_view.html index aff0216c..df898c2c 100644 --- a/zlt-web/layui-web/src/main/resources/static/pages/search/index_manager_view.html +++ b/zlt-web/layui-web/src/main/resources/static/pages/search/index_manager_view.html @@ -24,7 +24,7 @@ admin.req('api-search/admin/index', {'indexName':indexName}, function (data) { layer.closeAll('loading'); if (0 == data.resp_code) { - $('#data').html(syntaxHighlight(data.datas)); + $('#data').html(syntaxHighlight(data.data)); } else { layer.msg('获取索引信息失败', {icon: 2, time: 500}); } @@ -53,4 +53,4 @@ return '' + match + ''; }); } - \ No newline at end of file + diff --git a/zlt-web/layui-web/src/main/resources/static/pages/system/menus.html b/zlt-web/layui-web/src/main/resources/static/pages/system/menus.html index 23d3861e..0798ab8b 100644 --- a/zlt-web/layui-web/src/main/resources/static/pages/system/menus.html +++ b/zlt-web/layui-web/src/main/resources/static/pages/system/menus.html @@ -83,7 +83,7 @@ layer.closeAll('loading'); if (0 === data.resp_code) { let selected = false; - $.each(data.datas,function(index,item){ + $.each(data.data,function(index,item){ if (config.clientId === item.clientId) { selected = true; } else { @@ -185,4 +185,4 @@ renderTable(data.value); }); }); - \ No newline at end of file + diff --git a/zlt-web/layui-web/src/main/resources/static/pages/system/myInfo.html b/zlt-web/layui-web/src/main/resources/static/pages/system/myInfo.html index 97d8ca64..d539631f 100644 --- a/zlt-web/layui-web/src/main/resources/static/pages/system/myInfo.html +++ b/zlt-web/layui-web/src/main/resources/static/pages/system/myInfo.html @@ -59,7 +59,7 @@ admin.req('api-user/users/current', {}, function (data) { // 回显user数据 if (data && data.resp_code === 0) { - let user = data.datas; + let user = data.data; user.sex = user.sex.toString(); form.val('user-form', user); $('#user-form').attr('method', 'PUT'); @@ -75,7 +75,7 @@ $(".layui-nav-img").attr("src",$("[name=headImgUrl]").val()); layer.msg("操作成功", {icon: 1, time: 500}); - form.val('user-form',data.datas); + form.val('user-form',data.data); } else { layer.msg(data.resp_msg, {icon: 2, time: 500}); } @@ -109,4 +109,4 @@ }); }); - \ No newline at end of file + diff --git a/zlt-web/layui-web/src/main/resources/static/pages/system/role.html b/zlt-web/layui-web/src/main/resources/static/pages/system/role.html index 9c39bf88..f3ab10ec 100644 --- a/zlt-web/layui-web/src/main/resources/static/pages/system/role.html +++ b/zlt-web/layui-web/src/main/resources/static/pages/system/role.html @@ -101,7 +101,7 @@ layer.closeAll('loading'); if (0 === data.resp_code) { let selected = false; - $.each(data.datas,function(index,item){ + $.each(data.data,function(index,item){ if (config.clientId === item.clientId) { selected = true; } else { @@ -257,4 +257,4 @@ }); }); - \ No newline at end of file + diff --git a/zlt-web/layui-web/src/main/resources/static/pages/system/tokens.html b/zlt-web/layui-web/src/main/resources/static/pages/system/tokens.html index 1bbbe9c5..42ffda3c 100644 --- a/zlt-web/layui-web/src/main/resources/static/pages/system/tokens.html +++ b/zlt-web/layui-web/src/main/resources/static/pages/system/tokens.html @@ -62,7 +62,7 @@ layer.closeAll('loading'); if (0 === data.resp_code) { let selected = false; - $.each(data.datas,function(index,item){ + $.each(data.data,function(index,item){ if (config.clientId === item.clientId) { selected = true; } else { @@ -108,4 +108,4 @@ table.reload('tokens-table', {where: {tenantId: data.value}}); }); }); - \ No newline at end of file + diff --git a/zlt-web/layui-web/src/main/resources/static/pages/system/user_form.html b/zlt-web/layui-web/src/main/resources/static/pages/system/user_form.html index c2729323..916e71bd 100644 --- a/zlt-web/layui-web/src/main/resources/static/pages/system/user_form.html +++ b/zlt-web/layui-web/src/main/resources/static/pages/system/user_form.html @@ -58,8 +58,8 @@ if (0 == data.resp_code) { // 渲染多选下拉框 var roleSelectData = new Array(); - for (var i = 0; i < data.datas.length; i++) { - roleSelectData.push({name: data.datas[i].name, value: data.datas[i].id}); + for (var i = 0; i < data.data.length; i++) { + roleSelectData.push({name: data.data[i].name, value: data.data[i].id}); } formSelects.data('roleId', 'local', {arr: roleSelectData}); @@ -96,4 +96,4 @@ return false; }); }); - \ No newline at end of file + diff --git a/zlt-web/react-web/src/main/frontend/Dockerfile b/zlt-web/react-web/src/main/frontend/Dockerfile new file mode 100644 index 00000000..d559c4c4 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/Dockerfile @@ -0,0 +1,15 @@ +# 使用轻量级的 nginx 镜像 +FROM nginx:alpine + +# 复制构建后的文件到 nginx 目录 +COPY dist/ /usr/share/nginx/html/ + +# 复制 nginx 配置文件 +COPY nginx.conf /etc/nginx/conf.d/default.conf + +# 设置正确的权限 +RUN chown -R nginx:nginx /usr/share/nginx/html && \ + chmod -R 755 /usr/share/nginx/html + +# 暴露 8080 端口 +EXPOSE 8080 \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/config/config.ts b/zlt-web/react-web/src/main/frontend/config/config.ts index 28b143b0..3879f6bc 100644 --- a/zlt-web/react-web/src/main/frontend/config/config.ts +++ b/zlt-web/react-web/src/main/frontend/config/config.ts @@ -71,7 +71,7 @@ export default defineConfig({ }, ], nodeModulesTransform: { type: 'none' }, - mfsu: {}, + mfsu: false, webpack5: {}, exportStatic: {}, history: { diff --git a/zlt-web/react-web/src/main/frontend/config/defaultSettings.ts b/zlt-web/react-web/src/main/frontend/config/defaultSettings.ts index 9af42312..6ea9bca8 100644 --- a/zlt-web/react-web/src/main/frontend/config/defaultSettings.ts +++ b/zlt-web/react-web/src/main/frontend/config/defaultSettings.ts @@ -12,7 +12,7 @@ const Settings: LayoutSettings & { fixedHeader: false, fixSiderbar: true, colorWeak: false, - title: '开源项目演示环境', + title: 'G-Fly', pwa: false, logo: './logo.png', iconfontUrl: '', diff --git a/zlt-web/react-web/src/main/frontend/config/proxy.ts b/zlt-web/react-web/src/main/frontend/config/proxy.ts index 65f2c9c4..28ffaeca 100644 --- a/zlt-web/react-web/src/main/frontend/config/proxy.ts +++ b/zlt-web/react-web/src/main/frontend/config/proxy.ts @@ -9,26 +9,42 @@ export default { dev: { '/api-uaa/': { + // target: 'http://119.45.169.13:9900', target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-user/': { + // target: 'http://119.45.169.13:9900', target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-log/': { + // target: 'http://119.45.169.13:9900', target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-search/': { + // target: 'http://119.45.169.13:9900', target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-generator/': { - target: 'http://127.0.0.1:9900', + target: 'http://119.45.169.13:9900', + // target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-file/': { + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', + changeOrigin: true, + }, + '/api-order/': { + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', + changeOrigin: true, + }, + '/api-device/': { + // target: 'http://119.45.169.13:9900', target: 'http://127.0.0.1:9900', changeOrigin: true, }, diff --git a/zlt-web/react-web/src/main/frontend/config/routes.ts b/zlt-web/react-web/src/main/frontend/config/routes.ts index 88cec02b..66c8facd 100644 --- a/zlt-web/react-web/src/main/frontend/config/routes.ts +++ b/zlt-web/react-web/src/main/frontend/config/routes.ts @@ -36,6 +36,10 @@ path: '/system/myInfo.html', component: './system/UserInfo', }, + { + path: '/system/miniApp.html', + component: './system/MiniApp', + }, ], }, { @@ -47,6 +51,85 @@ } ], }, + { + path: '/device', + routes: [ + { + path: '/device/wayline.html', + component: './device/Wayline', + }, + { + path: '/device/device.html', + component: './device/Device', + }, + ] + }, + { + path: '/message', + routes: [ + { + path: '/message/message.html', + component: './message/index', + } + ], + }, + { + path: '/orders', + routes: [ + { + path: '/orders/order.html', + component: './orders/Order', + }, + { + path: '/orders/orderFiles.html', + component: './orders/OrderFile', + }, + { + path: '/orders/tourism.html', + component: './orders/Tourism', + }, + { + path: '/orders/qrcode.html', + component: './orders/Qrcode', + }, + { + path: '/orders/tourismFile.html', + component: './orders/TourismFile', + }, + { + path: '/orders/homeCarousel.html', + component: './orders/HomeCarousel', + }, + { + path: '/orders/refund.html', + component: './orders/Refund', + }, + { + path: '/orders/statistics.html', + component: './orders/statistics', + }, + { + path: '/orders/profitSharing.html', + component: './orders/ProfitSharing', + }, + { + path: '/orders/profit-sharing/statistics.html', + component: './orders/ProfitSharing/Statistics', + }, + { + path: '/orders/videoTemplate.html', + component: './orders/VideoTemplate', + }, + { + path: '/orders/editTask.html', + component: './orders/EditTask', + }, + { + path: '/orders/wxMessage.html', + component: './orders/WxMessage', + }, + ], + }, { path: '/search', routes: [ @@ -95,6 +178,12 @@ path: '/', redirect: '/welcome', }, + { + path: '/orders/edit-task', + name: '剪辑任务管理', + icon: 'VideoCameraOutlined', + component: './orders/EditTask', + }, { component: './404', }, diff --git a/zlt-web/react-web/src/main/frontend/deploy.sh b/zlt-web/react-web/src/main/frontend/deploy.sh new file mode 100644 index 00000000..ee875270 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/deploy.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +echo "开始部署前端项目..." + +# 首先构建项目 +echo "构建前端项目..." +npm run build + +# 检查构建是否成功 +if [ ! -d "dist" ]; then + echo "错误:dist 目录不存在,构建可能失败" + exit 1 +fi + +# 检查必要文件 +if [ ! -f "dist/index.html" ]; then + echo "错误:index.html 不存在,构建可能不完整" + exit 1 +fi + +echo "开始 Docker 部署..." + +# 停止并删除旧容器 +docker compose down + +# 清理旧的构建缓存 +docker builder prune -f + +# 重新构建并启动 +docker compose up -d --build + +# 检查容器状态 +docker compose ps + +# 验证部署 +echo "验证部署..." +curl -I http://localhost:8080 + +echo "部署完成!项目已启动在 8080 端口" + +# 显示容器日志 +docker compose logs frontend + +# 进入容器检查文件 +docker exec frontend ls -la /usr/share/nginx/html + +# 检查 nginx 配置 +docker exec frontend nginx -t + +# 查看 nginx 日志 +docker exec frontend cat /var/log/nginx/error.log \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/docker-compose.yml b/zlt-web/react-web/src/main/frontend/docker-compose.yml new file mode 100644 index 00000000..5c0c1a8b --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/docker-compose.yml @@ -0,0 +1,18 @@ +version: '3' +services: + frontend: + build: + context: . + dockerfile: Dockerfile + container_name: frontend + ports: + - "8080:8080" + volumes: + - ./nginx.conf:/etc/nginx/conf.d/default.conf + restart: always + networks: + - app-network + +networks: + app-network: + driver: bridge \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/nginx.conf b/zlt-web/react-web/src/main/frontend/nginx.conf new file mode 100644 index 00000000..fe1c34a1 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/nginx.conf @@ -0,0 +1,122 @@ +server { + listen 8080; + server_name localhost; + + # gzip 配置 + gzip on; + gzip_min_length 1k; + gzip_comp_level 6; + gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml; + gzip_vary on; + gzip_proxied any; + + root /usr/share/nginx/html/react-web; + index index.html; + + # 支持 history 路由 + location / { + try_files $uri $uri/ /index.html; + + # 添加必要的跨域和缓存控制头 + add_header Access-Control-Allow-Origin *; + # 调整缓存策略,例如对于静态资源可以缓存 + location ~* \.(css|js|svg|png|jpg|jpeg)$ { + expires 365d; + } + + # 添加安全相关头 + add_header X-Frame-Options SAMEORIGIN; + add_header X-Content-Type-Options nosniff; + add_header X-XSS-Protection "1; mode=block"; + } + + # API-UAA 服务代理 + location /api-uaa/ { + proxy_pass http://119.45.169.13:9900/api-uaa/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + + # 确保 Authorization 头可以传递 + proxy_set_header Authorization $http_authorization; + proxy_pass_header Authorization; + + # 处理 OPTIONS 请求 + if ($request_method = 'OPTIONS') { + add_header Access-Control-Allow-Origin *; + add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; + add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; + return 204; + } + } + + # 用户服务代理 + location /api-user/ { + proxy_pass http://119.45.169.13:9900/api-user/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + + # 确保 Authorization 头可以传递 + proxy_set_header Authorization $http_authorization; + proxy_pass_header Authorization; + + # 处理 OPTIONS 请求 + if ($request_method = 'OPTIONS') { + add_header Access-Control-Allow-Origin *; + add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; + add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; + return 204; + } + } + + # 其他 API 服务代理(如果需要) + location /api/ { + proxy_pass http://119.45.169.13:9900/; # 替换为实际的后端地址 + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + + # 添加跨域头 + add_header Access-Control-Allow-Origin *; + add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; + add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; + + # 处理 OPTIONS 请求 + if ($request_method = 'OPTIONS') { + return 204; + } + } + + # API 代理配置 + location /api-order/ { + proxy_pass http://119.45.169.13:9900/api-order/; # 替换为您的后端API地址 + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + + # 处理 OPTIONS 请求 + if ($request_method = 'OPTIONS') { + add_header Access-Control-Allow-Origin *; + add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; + add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; + return 204; + } + } + + # API 代理配置 + location /api-device/ { + proxy_pass http://119.45.169.13:9900/api-device/; # 替换为您的后端API地址 + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + + # 处理 OPTIONS 请求 + if ($request_method = 'OPTIONS') { + add_header Access-Control-Allow-Origin *; + add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; + add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; + return 204; + } + } +} \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/package.json b/zlt-web/react-web/src/main/frontend/package.json index bf5d20ca..713bb279 100644 --- a/zlt-web/react-web/src/main/frontend/package.json +++ b/zlt-web/react-web/src/main/frontend/package.json @@ -4,7 +4,7 @@ "private": true, "scripts": { "analyze": "cross-env ANALYZE=1 umi build", - "build": "umi build", + "build": "set NODE_OPTIONS=--openssl-legacy-provider && umi build", "deploy": "npm run build && npm run gh-pages", "dev": "npm run start:dev", "gh-pages": "gh-pages -d dist", @@ -21,8 +21,8 @@ "playwright": "playwright install && playwright test", "prettier": "prettier -c --write \"src/**/*\"", "serve": "umi-serve", - "start": "cross-env UMI_ENV=dev umi dev --port=8066", - "start:dev": "cross-env REACT_APP_ENV=dev MOCK=none UMI_ENV=dev umi dev", + "start": "set NODE_OPTIONS=--openssl-legacy-provider && cross-env UMI_ENV=dev umi dev --port=8066", + "start:dev": "set NODE_OPTIONS=--openssl-legacy-provider && cross-env REACT_APP_ENV=dev MOCK=none UMI_ENV=dev umi dev", "start:no-mock": "cross-env MOCK=none UMI_ENV=dev umi dev", "start:no-ui": "cross-env UMI_UI=none UMI_ENV=dev umi dev", "start:pre": "cross-env REACT_APP_ENV=pre UMI_ENV=dev umi dev", @@ -48,9 +48,12 @@ "@ant-design/charts": "^1.4.2", "@ant-design/icons": "^4.7.0", "@ant-design/pro-components": "1.1.1", + "@babel/runtime": "^7.27.0", + "@types/file-saver": "^2.0.7", "@umijs/route-utils": "^2.0.0", "antd": "^4.20.0", "classnames": "^2.3.0", + "file-saver": "^2.0.5", "lodash": "^4.17.21", "moment": "^2.29.0", "omit.js": "^2.0.2", @@ -61,10 +64,14 @@ "react-dev-inspector": "^1.7.0", "react-dom": "^17.0.0", "react-helmet-async": "^1.2.0", + "react-intl": "6.4.4", "react-json-tree": "^0.17.0", + "react-player": "^2.16.0", + "spark-md5": "^3.0.2", "treeify-js": "^1.0.8", "umi": "^3.5.0", - "uuid": "^9.0.0" + "uuid": "^9.0.0", + "xlsx": "^0.18.5" }, "devDependencies": { "@ant-design/pro-cli": "^2.1.0", @@ -86,7 +93,7 @@ "@umijs/preset-ant-design-pro": "^1.3.0", "@umijs/preset-dumi": "^1.1.0", "@umijs/preset-react": "^2.1.0", - "cross-env": "^7.0.0", + "cross-env": "^7.0.3", "cross-port-killer": "^1.3.0", "detect-installer": "^1.0.0", "eslint": "^7.32.0", diff --git a/zlt-web/react-web/src/main/frontend/src/app.tsx b/zlt-web/react-web/src/main/frontend/src/app.tsx index dc3e5353..da9d7335 100644 --- a/zlt-web/react-web/src/main/frontend/src/app.tsx +++ b/zlt-web/react-web/src/main/frontend/src/app.tsx @@ -38,7 +38,7 @@ export async function getInitialState(): Promise<{ try { const msg = await queryCurrentUser(); // TODO - return msg.datas; + return msg.data; } catch (error) { history.push(loginPath); } diff --git a/zlt-web/react-web/src/main/frontend/src/components/Footer/index.tsx b/zlt-web/react-web/src/main/frontend/src/components/Footer/index.tsx index 46953c09..667922a4 100644 --- a/zlt-web/react-web/src/main/frontend/src/components/Footer/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/components/Footer/index.tsx @@ -6,19 +6,19 @@ const Footer: React.FC = () => { const intl = useIntl(); const defaultMessage = intl.formatMessage({ id: 'app.copyright.produced', - defaultMessage: 'zlt版权所有:https://gitee.com/zlt2000/microservices-platform', + defaultMessage: '版权所有:https://gitee.com/L-Shilin/go-fly-platform-services.git', }); // const currentYear = new Date().getFullYear(); return ( , - href: 'https://github.com/zlt2000/microservices-platform', + href: 'https://gitee.com/L-Shilin/go-fly-platform-services.git', blankTarget: true, }, { diff --git a/zlt-web/react-web/src/main/frontend/src/components/RightContent/index.tsx b/zlt-web/react-web/src/main/frontend/src/components/RightContent/index.tsx index 94086d8a..b3aaa2f1 100644 --- a/zlt-web/react-web/src/main/frontend/src/components/RightContent/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/components/RightContent/index.tsx @@ -1,14 +1,16 @@ -import { GithubOutlined, QuestionCircleOutlined } from '@ant-design/icons'; -import { Space } from 'antd'; +import { GithubOutlined, QuestionCircleOutlined, BellOutlined } from '@ant-design/icons'; +import { Space, Badge } from 'antd'; import React from 'react'; import { useModel } from 'umi'; import AvatarDropdown from './AvatarDropdown'; import styles from './index.less'; +import { history } from 'umi'; export type SiderTheme = 'light' | 'dark'; const GlobalHeaderRight: React.FC = () => { const { initialState } = useModel('@@initialState'); + const { unreadCount } = useModel('useMessage'); if (!initialState || !initialState.settings) { return null; @@ -61,6 +63,14 @@ const GlobalHeaderRight: React.FC = () => { > + history.push('/message')} + > + + + + ); diff --git a/zlt-web/react-web/src/main/frontend/src/config/auth.ts b/zlt-web/react-web/src/main/frontend/src/config/auth.ts new file mode 100644 index 00000000..bb378a38 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/config/auth.ts @@ -0,0 +1,4 @@ +export const AUTH_CONFIG = { + basicToken: 'Basic d2ViQXBwOndlYkFwcA==', + // basicToken: 'Basic Z2ZhcHA6SWtpbmd0ZWNAMjAyMA==', // 备用token +}; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/locales/zh-CN.ts b/zlt-web/react-web/src/main/frontend/src/locales/zh-CN.ts index dcd4aca0..20424ad1 100644 --- a/zlt-web/react-web/src/main/frontend/src/locales/zh-CN.ts +++ b/zlt-web/react-web/src/main/frontend/src/locales/zh-CN.ts @@ -11,7 +11,7 @@ export default { 'layout.user.link.help': '帮助', 'layout.user.link.privacy': '隐私', 'layout.user.link.terms': '条款', - 'app.copyright.produced': 'zlt版权所有:https://gitee.com/zlt2000/microservices-platform', + 'app.copyright.produced': '版权所有:https://gitee.com/L-Shilin/go-fly-platform-services.git', 'app.preview.down.block': '下载此页面到本地项目', 'app.welcome.link.fetch-blocks': '获取全部区块', 'app.welcome.link.block-list': '基于 block 开发,快速构建标准页面', diff --git a/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts b/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts index fecb70a4..4f640e8b 100644 --- a/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts +++ b/zlt-web/react-web/src/main/frontend/src/locales/zh-CN/menu.ts @@ -49,4 +49,5 @@ export default { 'menu.editor.flow': '流程编辑器', 'menu.editor.mind': '脑图编辑器', 'menu.editor.koni': '拓扑编辑器', + 'menu.首页': '首页', }; diff --git a/zlt-web/react-web/src/main/frontend/src/models/useMessage.ts b/zlt-web/react-web/src/main/frontend/src/models/useMessage.ts new file mode 100644 index 00000000..fc37796e --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/models/useMessage.ts @@ -0,0 +1,27 @@ +import { useState, useEffect } from 'react'; +import { getMessages } from '@/services/message/api'; + +export default () => { + const [unreadCount, setUnreadCount] = useState(0); + + const fetchUnreadCount = async () => { + try { + const response = await getMessages({ status: 0, pageSize: 1 }); + setUnreadCount(response.total || 0); + } catch (error) { + console.error('获取未读消息数量失败:', error); + } + }; + + useEffect(() => { + fetchUnreadCount(); + // 设置定时刷新 + const timer = setInterval(fetchUnreadCount, 60000); // 每分钟刷新一次 + return () => clearInterval(timer); + }, []); + + return { + unreadCount, + refreshUnreadCount: fetchUnreadCount, + }; +}; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.less b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.less index d0010257..9ded211c 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.less +++ b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.less @@ -1,11 +1,279 @@ @import (reference) '~antd/es/style/themes/index'; +@import '~antd/es/style/themes/default.less'; -.stat { - margin-top: @margin-md; - padding: @padding-md; - background-color: @white; +.container { + :global { + .ant-card { + border-radius: 8px; + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05); + transition: all 0.3s; + + &:hover { + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.09); + } + } + } +} + +.statCard { + height: 180px; + + .statHeader { + display: flex; + align-items: center; + margin-bottom: 16px; + + span { + margin-left: 8px; + font-size: 16px; + font-weight: 500; + } + } + + .subStats { + margin-top: 16px; + display: flex; + justify-content: space-between; + align-items: flex-end; + + :global { + .ant-statistic { + flex: 1; + } + + .ant-progress { + width: 100px; + margin-left: 16px; + } + } + } +} + +// 图标样式 +.iconOrders { + font-size: 24px; + color: #1890ff; +} + +.iconIncome { + font-size: 24px; + color: #52c41a; +} + +.iconWayline { + font-size: 24px; + color: #722ed1; +} + +.iconDevice { + font-size: 24px; + color: #faad14; +} + +.trend { + font-size: 14px; + margin-left: 8px; + color: #52c41a; +} + +.chartsRow { + margin-top: 16px; +} + +.businessRow { + margin-top: 16px; +} + +.rankList { + .rankItem { + display: flex; + align-items: center; + padding: 12px 0; + border-bottom: 1px solid #f0f0f0; + + &:last-child { + border-bottom: none; + } + + .rankNum { + width: 20px; + height: 20px; + line-height: 20px; + text-align: center; + background: #fafafa; + border-radius: 10px; + margin-right: 16px; + font-size: 12px; + color: #8c8c8c; + + &.topThree { + color: #fff; + &:nth-child(1) { background: #f5222d; } + &:nth-child(2) { background: #fa8c16; } + &:nth-child(3) { background: #faad14; } + } + } + + .rankName { + flex: 1; + color: rgba(0, 0, 0, 0.85); + } + + .rankValue { + color: rgba(0, 0, 0, 0.45); + } + } +} + +// 响应式调整 +@media screen and (max-width: 768px) { + .statCard { + height: auto; + margin-bottom: 16px; + } + + .chartsRow, .businessRow { + margin-top: 8px; + } } .pie { margin-top: @margin-md; } + +.chartCard { + margin: 24px 0; + background: #fff; + border-radius: 8px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); + + :global { + .ant-tabs-nav { + margin-bottom: 16px; + padding: 0 24px; + } + + .ant-tabs-tab { + padding: 12px 0; + font-size: 15px; + + &:hover { + color: @primary-color; + } + } + + .ant-tabs-tab-active { + .ant-tabs-tab-btn { + font-weight: 500; + } + } + + .ant-empty { + padding: 32px 0; + } + } +} + +.pieRow { + margin-bottom: 24px; +} + +.pieCard { + height: 100%; + border-radius: 8px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); + + :global { + .ant-card-head { + padding: 0 24px; + border-bottom: 1px solid @border-color-split; + + .ant-card-head-title { + padding: 16px 0; + font-size: 16px; + font-weight: 500; + } + } + + .ant-card-body { + padding: 24px; + } + + .ant-empty { + padding: 32px 0; + } + } +} + +:global { + .ant-pro-card { + border-radius: 8px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); + } + + .ant-statistic-title { + font-size: 15px; + margin-bottom: 8px; + } + + .ant-statistic-content { + font-size: 24px; + font-weight: 500; + + &-value { + color: @heading-color; + } + } + + .ant-pro-card-statistic-description { + margin-top: 8px; + } + + .ant-skeleton { + padding: 24px; + } +} + +@media screen and (max-width: @screen-md) { + .pieRow { + .pieCard { + margin-bottom: 16px; + } + } +} + +.statisticIcon { + color: #1890ff; + font-size: 20px; +} + +.statisticGroup { + margin-top: 24px; +} + +.chartRow { + margin-top: 24px; + + .ant-card { + height: 100%; + } +} + +.tourismCard { + margin-top: 24px; +} + +// 响应式调整 +@media screen and (max-width: 768px) { + .statisticGroup { + margin-top: 16px; + } + + .chartRow { + margin-top: 16px; + } + + .tourismCard { + margin-top: 16px; + } +} diff --git a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx index c9d26202..ad302e3f 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/Welcome.tsx @@ -1,224 +1,256 @@ -import { PageContainer, StatisticCard } from '@ant-design/pro-components'; -import { Card, Tag, Space, Tabs, Col, Row } from 'antd'; -import RcResizeObserver from 'rc-resize-observer'; +import { PageContainer } from '@ant-design/pro-components'; +import { Card, Row, Col, Statistic, Progress, Typography } from 'antd'; import React, { useState, useEffect } from 'react'; -import { statistic } from '@/services/welcome/api'; -import { Area, Pie } from '@ant-design/plots'; +import { dashboard } from '@/services/orders/api'; +import { Area, Column, Pie } from '@ant-design/plots'; +import { + ShoppingCartOutlined, + RocketOutlined, + MobileOutlined, + UserOutlined, + RiseOutlined, + PayCircleOutlined, +} from '@ant-design/icons'; import styles from './Welcome.less'; -const { Divider } = StatisticCard; +const { Title } = Typography; + +interface Statistics { + totalOrders: number; + todayOrders: number; + orderGrowth: number; + completionRate: number; + totalAmount: number; + todayAmount: number; + targetCompletion: number; + totalWaylines: number; + activeWaylines: number; + waylineUsage: number; + totalDevices: number; + onlineDevices: number; + deviceOnlineRate: number; + orderTrend: Array<{ + date: string; + type: string; + value: number; + }>; + deviceDistribution: Array<{ + type: string; + value: number; + }>; + incomeData: Array<{ + type: string; + value: number; + }>; + tourismRanking: Array<{ + id: string; + name: string; + value: number; + }>; +} const Welcome: React.FC = () => { - const [responsive, setResponsive] = useState(false); - const [statistics, setStatistics] = useState({}); - const [weeks, setWeeks] = useState([]); - const [days, setDays] = useState([]); + const [loading, setLoading] = useState(true); + const [statistics, setStatistics] = useState({}); - const mapWeek = (result: WELCOME.Statistic) => { - const { statWeek_items, statWeek_pv, statWeek_uv } = result; - if (statWeek_items && statWeek_pv && statWeek_uv) { - const weekData = statWeek_pv - .map((pv, index) => { - return { type: '访问量(PV)', date: statWeek_items[index], value: pv }; - }) - .concat( - statWeek_uv.map((uv, index) => { - return { type: '独立用户(UV)', date: statWeek_items[index], value: uv }; - }), - ); - setWeeks(weekData); - } - }; - - const mapDay = (result: WELCOME.Statistic) => { - const { statDate_items, statDate_pv, statDate_uv } = result; - if (statDate_items && statDate_pv && statDate_uv) { - const dayData = statDate_pv - .map((pv, index) => { - return { type: '访问量(PV)', date: statDate_items[index], value: pv }; - }) - .concat( - statDate_uv.map((uv, index) => { - return { type: '独立用户(UV)', date: statDate_items[index], value: uv }; - }), - ); - setDays(dayData); + const fetchData = async () => { + try { + setLoading(true); + const result = await dashboard(); + if (result.resp_code === 0) { + setStatistics(result.data); + } + } catch (error) { + console.error('获取统计数据失败:', error); + } finally { + setLoading(false); } }; useEffect(() => { - (async () => { - const result = await statistic(); - if (result) { - setStatistics(result); - mapWeek(result); - mapDay(result); - } - })(); + fetchData(); + const timer = setInterval(fetchData, 5 * 60 * 1000); + return () => clearInterval(timer); }, []); + // 更新数据访问方式 + const orderStats = statistics.orderStats || {}; + const incomeStats = statistics.incomeStats || {}; + const waylineStats = statistics.waylineStats || {}; + const deviceStats = statistics.deviceStats || {}; + const chartStats = statistics.chartStats || {}; + + // 订单趋势配置 + const orderTrendConfig = { + data: chartStats.orderTrend || [], + xField: 'date', + yField: 'value', + seriesField: 'type', + smooth: true, + animation: true, + legend: { + position: 'top', + }, + areaStyle: { + fillOpacity: 0.6, + }, + }; + + // 设备分布配置 + const deviceDistConfig = { + data: chartStats.deviceDistribution || [], + angleField: 'value', + colorField: 'type', + radius: 0.8, + label: { + type: 'outer', + content: '{name} {percentage}', + }, + }; + + // 收入统计配置 + const incomeConfig = { + data: chartStats.incomeData || [], + xField: 'type', + yField: 'value', + label: { + position: 'middle', + style: { + fill: '#FFFFFF', + opacity: 0.6, + }, + }, + }; + return ( - - 简单 - 高效 - - } - > - { - setResponsive(offset.width < 596); - }} - > - - - 在线人数时 - - ), - value: statistics.currHour_uv, - }} - /> - - - PV天 - - ), - value: statistics.currDate_pv, - }} - /> - - - UV天 - - ), - value: statistics.currDate_uv, - }} - /> - - - 周访问量周 - - ), - value: statistics.currWeek_pv, - }} - /> - - - 月访问量月 - - ), - value: statistics.currMonth_pv, - }} - /> - - - - - - - - - - - - - - + {/* 核心指标 */} + + + +
+ + 订单总览 +
+ + {orderStats.orderGrowth || 0}% + + } /> +
+ + +
- - - + +
+ + 收入统计 +
+ +
+ + +
+
+ + + + +
+ + 航线概况 +
+ +
+ + +
+
+ + + + +
+ + 设备状态 +
+ +
+ + +
+
+ +
+ + {/* 图表展示 */} + + + + + + + + + + + + + + {/* 业务数据 */} + + + + + + + + +
+ {(statistics.tourismRanking || []).map((item: any, index: number) => ( +
+ + {index + 1} + + {item.name} + {item.value} +
+ ))} +
diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/DeviceControlPanel.less b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/DeviceControlPanel.less new file mode 100644 index 00000000..7e3a9392 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/DeviceControlPanel.less @@ -0,0 +1,27 @@ +.videoCard { + margin-bottom: 16px; + + :global { + .ant-card-body { + padding: 0; + } + } +} + +.controlCard { + margin-bottom: 16px; + + :global { + .ant-space { + width: 100%; + } + } +} + +.statusCard { + :global { + .ant-statistic { + margin-bottom: 16px; + } + } +} \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/DeviceControlPanel.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/DeviceControlPanel.tsx new file mode 100644 index 00000000..acaf8200 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/DeviceControlPanel.tsx @@ -0,0 +1,231 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { Modal, Tabs, Button, Space, Card, Row, Col, Statistic, message, Badge } from 'antd'; +import { + PlayCircleOutlined, + PauseOutlined, + CameraOutlined, + VideoCameraOutlined, + HomeOutlined, + PauseCircleOutlined, + ControlOutlined +} from '@ant-design/icons'; +import ReactPlayer from 'react-player'; +import { getStreamUrls } from '@/services/device/api'; +import styles from './DeviceControlPanel.less'; + +interface DeviceControlPanelProps { + visible: boolean; + onClose: () => void; + deviceSn: string; +} + +const DeviceControlPanel: React.FC = ({ visible, onClose, deviceSn }) => { + const [streamUrls, setStreamUrls] = useState(null); + const [isPlaying, setIsPlaying] = useState(true); + const [cameraMode, setCameraMode] = useState(0); // 0=拍照,1=录像 + const [isRecording, setIsRecording] = useState(false); + const [wsConnected, setWsConnected] = useState(false); + const wsRef = useRef(null); + const playerRef = useRef(null); + + // 初始化WebSocket连接 + useEffect(() => { + if (visible) { + const ws = new WebSocket('ws://your-websocket-server'); + wsRef.current = ws; + + ws.onopen = () => { + setWsConnected(true); + message.success('设备连接成功'); + }; + + ws.onclose = () => { + setWsConnected(false); + message.error('设备连接断开'); + }; + + ws.onerror = (error) => { + console.error('WebSocket错误:', error); + message.error('设备连接错误'); + }; + + return () => { + ws.close(); + }; + } + }, [visible]); + + // 获取视频流地址 + useEffect(() => { + if (visible) { + getStreamUrls(deviceSn).then(res => { + if (res.resp_code === 0) { + setStreamUrls(res.data); + } + }); + } + }, [visible, deviceSn]); + + // 发送控制指令 + const sendControlCommand = (method: string, data: any = {}) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + message.error('设备未连接'); + return; + } + + const command = { + type: 'sub', + topic: `/device-message-sender/D-Dock2/${deviceSn}`, + parameter: { + messageType: 'WRITE_PROPERTY', + properties: { + method, + data + }, + headers: { + async: false + } + }, + id: `cmd_${Date.now()}` + }; + + wsRef.current.send(JSON.stringify(command)); + }; + + // 控制按钮事件处理 + const handleTakePhoto = () => { + sendControlCommand('camera_photo_take'); + message.success('拍照指令已发送'); + }; + + const handleStartRecording = () => { + sendControlCommand('camera_recording_start'); + setIsRecording(true); + message.success('开始录像'); + }; + + const handleStopRecording = () => { + sendControlCommand('camera_recording_stop'); + setIsRecording(false); + message.success('停止录像'); + }; + + const handleReturnHome = () => { + sendControlCommand('return_home'); + message.success('返航指令已发送'); + }; + + const handlePauseTask = () => { + sendControlCommand('flighttask_pause'); + message.success('暂停任务指令已发送'); + }; + + const handleEnterDRCMode = () => { + sendControlCommand('drc_mode_enter'); + message.success('进入指令飞行模式'); + }; + + return ( + + 设备控制面板 + + + } + open={visible} + onCancel={onClose} + width={1200} + footer={null} + > + + + + {streamUrls && ( + + )} + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; + +export default DeviceControlPanel; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/UpdateForm.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/UpdateForm.tsx new file mode 100644 index 00000000..c7e2c303 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/UpdateForm.tsx @@ -0,0 +1,91 @@ +import { + ModalForm, + ProForm, + ProFormText, + ProFormSelect, + ProFormTextArea, +} from '@ant-design/pro-components'; +import React from 'react'; + +// 设备类型常量 +const DEVICE_TYPE = { + DOCK: 1, + DRONE: 2, + REMOTE_CONTROL: 3, +} as const; + +export type FormValueType = { + id?: string; + deviceSn?: string; + deviceName?: string; + nickname?: string; + deviceType?: number; + firmwareVersion?: string; + deviceDesc?: string; +} & Partial; + +export type UpdateFormProps = { + onSubmit: (values: FormValueType) => Promise; + onVisibleChange: (visible: boolean) => void; + updateModalVisible: boolean; + values: Partial; +}; + +const UpdateForm: React.FC = (props) => { + const { updateModalVisible, onVisibleChange, onSubmit, values } = props; + + return ( + + + + + + + + + + + ); +}; + +export default UpdateForm; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/VideoPlayer.less b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/VideoPlayer.less new file mode 100644 index 00000000..421b878b --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/VideoPlayer.less @@ -0,0 +1,20 @@ +.playerContainer { + .controls { + margin-bottom: 16px; + padding: 8px; + background: #f5f5f5; + border-radius: 4px; + } + + :global { + .ant-tabs-content { + background: #000; + border-radius: 4px; + overflow: hidden; + } + + .ant-tabs-tab { + margin: 0 16px 0 0; + } + } +} \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/VideoPlayer.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/VideoPlayer.tsx new file mode 100644 index 00000000..57ac3f80 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/VideoPlayer.tsx @@ -0,0 +1,237 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { Modal, Tabs, Button, Space, Select, message, Badge } from 'antd'; +import ReactPlayer from 'react-player'; +import { VideoCameraOutlined, DownloadOutlined, PauseOutlined, PlayCircleOutlined } from '@ant-design/icons'; +import styles from './VideoPlayer.less'; + +interface VideoPlayerProps { + visible: boolean; + onClose: () => void; + streamUrls: { + playFlvUrl: string; + playM3u8Url: string; + playRtmpUrl: string; + }; + deviceSn: string; +} + +const VideoPlayer: React.FC = ({ visible, onClose, streamUrls, deviceSn }) => { + const [activeTab, setActiveTab] = useState('flv'); + const [isPlaying, setIsPlaying] = useState(true); + const [isRecording, setIsRecording] = useState(false); + const [streamStatus, setStreamStatus] = useState<'online' | 'offline'>('offline'); + const [quality, setQuality] = useState('high'); + const playerRef = useRef(null); + const mediaRecorderRef = useRef(null); + const recordedChunksRef = useRef([]); + + // 检查流状态 + const checkStreamStatus = async () => { + try { + const response = await fetch(streamUrls.playFlvUrl, { method: 'HEAD' }); + setStreamStatus(response.ok ? 'online' : 'offline'); + } catch (error) { + setStreamStatus('offline'); + } + }; + + // 定期检查流状态 + useEffect(() => { + if (visible) { + checkStreamStatus(); + const interval = setInterval(checkStreamStatus, 30000); // 每30秒检查一次 + return () => clearInterval(interval); + } + }, [visible, streamUrls]); + + // 开始录制 + const startRecording = () => { + if (playerRef.current) { + const stream = playerRef.current.getInternalPlayer().captureStream(); + const mediaRecorder = new MediaRecorder(stream, { + mimeType: 'video/webm;codecs=vp9', + }); + + mediaRecorder.ondataavailable = (event) => { + if (event.data.size > 0) { + recordedChunksRef.current.push(event.data); + } + }; + + mediaRecorder.onstop = () => { + const blob = new Blob(recordedChunksRef.current, { type: 'video/webm' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `recording-${deviceSn}-${new Date().toISOString()}.webm`; + a.click(); + URL.revokeObjectURL(url); + recordedChunksRef.current = []; + }; + + mediaRecorderRef.current = mediaRecorder; + mediaRecorder.start(); + setIsRecording(true); + } + }; + + // 停止录制 + const stopRecording = () => { + if (mediaRecorderRef.current && isRecording) { + mediaRecorderRef.current.stop(); + setIsRecording(false); + } + }; + + // 处理播放器错误 + const handleError = (error: any) => { + console.error('播放器错误:', error); + message.error('视频流播放出错,请检查网络连接或刷新重试'); + }; + + // 处理播放器就绪 + const handleReady = () => { + message.success('视频流已就绪'); + }; + + // 获取当前播放的URL + const getCurrentUrl = () => { + switch (activeTab) { + case 'flv': + return streamUrls.playFlvUrl; + case 'hls': + return streamUrls.playM3u8Url; + case 'rtmp': + return streamUrls.playRtmpUrl; + default: + return streamUrls.playFlvUrl; + } + }; + + // 根据质量设置播放器配置 + const getPlayerConfig = () => { + const baseConfig = { + controls: true, + width: '100%', + height: 450, + playing: isPlaying, + onError: handleError, + onReady: handleReady, + ref: playerRef, + }; + + switch (quality) { + case 'low': + return { + ...baseConfig, + config: { + file: { + attributes: { + style: { + width: '100%', + height: '100%', + }, + }, + forceVideo: true, + forceHLS: true, + hlsOptions: { + maxBufferLength: 30, + maxMaxBufferLength: 60, + maxBufferSize: 0, + maxBufferHole: 0.5, + }, + }, + }, + }; + case 'high': + default: + return baseConfig; + } + }; + + return ( + + 设备视频流 + + + } + open={visible} + onCancel={onClose} + width={800} + footer={null} + > +
+
+ + + +