This commit is contained in:
fallen-angle
2022-05-16 19:55:59 +08:00
parent 7598280fc1
commit 9e3638885d
34 changed files with 3623 additions and 115 deletions

View File

@@ -39,8 +39,8 @@ func listArticles(isPublish int, createUser int) *[]models.ListArticle {
}
//SaveArticle save the articles
func SaveArticle(article map[string]interface{}) (ok bool) {
models.BeforeSave(article, -1)
func SaveArticle(claims models.TokenClaims, article map[string]interface{}) (ok bool) {
models.BeforeSave(article, claims.ID)
ok, rows := models.Upsert[models.BackArticle](article)
return ok && rows != 0
}

View File

@@ -10,6 +10,7 @@ import (
"time"
)
//fakerGetRequest Get data from faker
func fakerGetRequest(uri string) string {
resStr := utils.GetWhioutHeader(global.FACKER_HOST + uri)
var res utils.GinResponse
@@ -18,6 +19,7 @@ func fakerGetRequest(uri string) string {
return string(dataStr)
}
//queryHotelContacts Hotel contacts
func queryHotelContacts(identification string) []models.HotelContactRequest {
dataStr := fakerGetRequest("query/contacts/hotel/" + identification)
var data []models.HotelContactRequest
@@ -28,6 +30,7 @@ func queryHotelContacts(identification string) []models.HotelContactRequest {
return data
}
//queryRailwayContacts Railway contacts
func queryRailwayContacts(identification string) []models.RailwayContactRequest {
dataStr := fakerGetRequest("query/contacts/railway/" + identification)
var data []models.RailwayContactRequest
@@ -38,7 +41,8 @@ func queryRailwayContacts(identification string) []models.RailwayContactRequest
return data
}
func queryPatients(identification string) []models.PatientRequest {
//queryPatients Patients
func QueryPatients(identification string) []models.PatientRequest {
dataStr := fakerGetRequest("query/contacts/railway/" + identification)
var data []models.PatientRequest
err := json.Unmarshal([]byte(dataStr), &data)
@@ -48,6 +52,7 @@ func queryPatients(identification string) []models.PatientRequest {
return data
}
//queryContacts Resolve the diffrent of hotel and railway request
func queryContacts(identification string) []models.BackObservation {
hotelContacts := queryHotelContacts(identification)
railwayContacts := queryRailwayContacts(identification)
@@ -55,11 +60,13 @@ func queryContacts(identification string) []models.BackObservation {
return observations
}
//splitFakerAddress Extract the region
func splitFakerAddress(fakerAddress string) string {
addresses := strings.Split(fakerAddress, " ")
return addresses[1] + " " + addresses[2]
}
//fakerContacts2Observations Convvert structs
func fakerContacts2Observations(contacts any) []models.BackObservation {
var observations []models.BackObservation
switch contacts.(type) {

View File

@@ -4,6 +4,7 @@ import (
"nCovTrack-Backend/models"
)
//InsertLocation Insert locations
func InsertLocation(claims models.TokenClaims, locationJMap map[string]interface{}) bool {
locationCMap := models.MapJ2c[models.BackLocation](locationJMap, true)
models.BeforeSave(locationCMap, claims.ID)
@@ -11,11 +12,13 @@ func InsertLocation(claims models.TokenClaims, locationJMap map[string]interface
return (ok && rowsAffected != 0)
}
//ListLocation List locations
func ListLocation(queryJMap map[string]any) *[]map[string]any {
queryCMap := models.MapJ2c[models.BackLocation](queryJMap, true)
return models.ListField[models.BackLocation]([]map[string]any{queryCMap}, true, "is_delete")
}
//DeleteLocation Delete locations
func DeleteLocation(id int) bool {
ok, rowsAffected := models.DeleteById[models.BackLocation](id)
return (ok && rowsAffected != 0)

View File

@@ -4,10 +4,12 @@ import (
"fmt"
"nCovTrack-Backend/global"
"nCovTrack-Backend/models"
"nCovTrack-Backend/service/notify"
"nCovTrack-Backend/utils"
"time"
)
//PullFromFaker Pull observations from faker system
func PullFromFaker(claims models.TokenClaims, patientId int) int64 {
// Get patient's identification by id
queryMap := []map[string]interface{}{{"id": patientId}}
@@ -28,31 +30,39 @@ func PullFromFaker(claims models.TokenClaims, patientId int) int64 {
observationsCMap := models.MapsJ2c[models.BackObservation](observationsJMap, false)
models.BeforeBatchSave(&observationsCMap, claims.ID)
_, rowsAffected := models.BatchInsert[models.BackObservation](observationsCMap)
// Generate situation record
// Generate situation record and send notify to the region
if rowsAffected != 0 {
pullSituationRecord(claims, observations)
pullNotify(observations)
}
return rowsAffected
}
func ListObservation(jsonMap map[string]interface{}) []models.ListObeservation {
//ListObservation list observations with query
func ListObservation(jsonMap map[string]interface{}) []models.ListObservation {
colMap := models.MapJ2c[models.BackObservation](jsonMap, true)
queryMap := []map[string]interface{}{colMap}
return listObservation(queryMap)
}
//GetObservation get observation by id
func GetObservation(id int) map[string]interface{} {
// Obseration
observationCMap := models.GetField[models.BackObservation]([]map[string]interface{}{{"id": id}}, true, "is_delete")
observationJMap := models.MapC2j[models.BackObservation](observationCMap, true)
// Pcr record
pcrRecordCMap := models.ListField[models.BackPcr]([]map[string]interface{}{{"observation": id}}, true, "is_delete")
pcrRecordJMap := models.MapsC2j[models.BackPcr](*pcrRecordCMap, true)
// Situation record
situationRecordCMap := models.ListField[models.BackSituationRecord]([]map[string]interface{}{{"observation": id}}, true, "is_delete")
situationRecordJMap := models.MapsC2j[models.BackSituationRecord](*situationRecordCMap, true)
// Assemble
observationJMap["pcrRecord"] = pcrRecordJMap
observationJMap["situationRecord"] = situationRecordJMap
return observationJMap
}
//InsertObservation add observation
func InsertObservation(claims models.TokenClaims, jsonMap map[string]interface{}) bool {
colMap := models.MapJ2c[models.BackObservation](jsonMap, true)
models.BeforeSave(colMap, claims.ID)
@@ -65,17 +75,103 @@ func InsertObservation(claims models.TokenClaims, jsonMap map[string]interface{}
}
func UpdateObservation(claims models.TokenClaims, jsonMap map[string]any) bool {
// Pre actions
colMap := models.MapJ2c[models.BackObservation](jsonMap, true)
models.BeforeSave(colMap, claims.ID)
oldMap := models.Get[models.BackObservation]([]map[string]interface{}{{"id": jsonMap["id"]}})
insertSituationRecord(claims, oldMap, colMap)
return false
queryMap := []map[string]interface{}{{"id": jsonMap["id"]}}
// Get old record
oldMap := models.Get[models.BackObservation](queryMap)
if oldMap == nil || len(oldMap) == 0 {
return false
}
// Deal with region update
if colMap["region"] != nil && oldMap["region"].(string) != colMap["region"].(string) {
updateObservationRegion(colMap["region"].(string))
}
// Deal with situation update
if colMap["health_situation"] != nil && int(colMap["health_situation"].(float64)) != oldMap["health_situation"].(int) ||
colMap["measure_situation"] != nil && int(colMap["measure_situation"].(float64)) != oldMap["measure_situation"].(int) {
updateSituation(claims, oldMap, colMap)
}
ok, rowsAffected := models.Update[models.BackObservation](queryMap, colMap)
return ok && rowsAffected != 0
}
// listObservation the queryMap need with table name
// @Param queryMap the colMap of models.BackObservation
func listObservation(queryMap []map[string]interface{}) []models.ListObeservation {
var observations []models.ListObeservation
//TreeifyObservations get the transmission chains of observations
// Param direction: up, down, all
func TreeifyObservations(observationId int, direction string) *models.TreeObservation {
// Get arrays form back observation
var observations []models.BackObservation
if direction != "down" {
observations = append(observations, treeifyObservations(observationId, true)...)
}
if direction != "up" {
observations = append(observations, treeifyObservations(observationId, false)...)
}
// Treeify
observationMap := map[int]*models.TreeObservation{}
for _, observation := range observations {
observationMap[observation.ID] = &models.TreeObservation{
ID: observation.ID,
Name: observation.Name,
Age: observation.Age,
Sex: observation.Sex,
Phone: observation.Phone,
Identification: observation.Identification,
ContactPerson: observation.ContactPerson,
Region: observation.Region,
Address: observation.Address,
HealthSituation: observation.HealthSituation,
HealthChangeTime: observation.HealthChangeTime,
CreateUser: observation.CreateUser,
CreateTime: observation.CreateTime,
ModifyUser: observation.ModifyUser,
ModifyTime: observation.ModifyTime,
}
}
var rootKey int
for k := range observationMap {
parentId := observationMap[k].ContactPerson
parent := observationMap[parentId]
if parent == nil {
rootKey = k
continue
}
parent.Children = append(parent.Children, observationMap[k])
}
return observationMap[rootKey]
}
//treeifyObservations query tree data from db
// Param direction up: true, down: false
func treeifyObservations(observationId int, direction bool) []models.BackObservation {
var res []models.BackObservation
var directionCond string
if direction {
directionCond = "p.id = cte.contact_person"
} else {
directionCond = "cte.id = p.contact_person"
}
querySql := fmt.Sprintf(`
WITH RECURSIVE cte (id, name, age, sex, phone, identification, contact_person, region, address, health_situation, health_change_time, trajectory, create_user, modify_user, create_time, modify_time) AS (
SELECT id, name, age, sex, phone, identification, contact_person, region, address, health_situation, health_change_time, trajectory, create_user, modify_user, create_time, modify_time
FROM back_observation
WHERE contact_person = ?
UNION ALL
SELECT p.id, p.name, p.age, p.sex, p.phone, p.identification, p.contact_person, p.region, p.address, p.health_situation, p.health_change_time, p.trajectory, p.create_user, p.modify_user, p.create_time, p.modify_time
FROM back_observation p
INNER JOIN cte ON %s
)
SELECT * FROM cte
`, directionCond)
global.Db.Model(models.BackObservation{}).Raw(querySql, observationId).Scan(&res)
return res
}
//listObservation the queryMap need with table name
// Param queryMap the colMap of models.BackObservation
func listObservation(queryMap []map[string]interface{}) []models.ListObservation {
var observations []models.ListObservation
tx := global.Db.Model(new((models.BackObservation))).
Select("back_observation.*, back_pcr.detect_time AS pcr_time, detect_result AS pcr_result," +
"back_situation_record.create_time AS record_time, back_situation_record.record AS record").
@@ -94,6 +190,7 @@ func listObservation(queryMap []map[string]interface{}) []models.ListObeservatio
return observations
}
//pullSituationRecord push situation record after pull observations
func pullSituationRecord(claims models.TokenClaims, observations []models.BackObservation) {
// Query observations' id
var identifications []string
@@ -104,7 +201,7 @@ func pullSituationRecord(claims models.TokenClaims, observations []models.BackOb
observationMaps := models.ListField[models.BackObservation](queryMap, false, "id", "identification")
// Assemble records
var records []models.BackSituationRecord
recordContent := record00_20()
recordContent := record___20()
for _, observationMap := range *observationMaps {
record := models.BackSituationRecord{Observation: observationMap["id"].(int), Record: recordContent}
records = append(records, record)
@@ -115,20 +212,87 @@ func pullSituationRecord(claims models.TokenClaims, observations []models.BackOb
recordsCMaps := models.MapsJ2c[models.BackSituationRecord](recordsJMaps, true)
models.BeforeBatchSave(&recordsCMaps, claims.ID)
models.BatchInsert[models.BackSituationRecord](recordsCMaps)
// Notify the admin of pull region
// Send email to the region admin
}
//pullNotify send notify after pull observations
func pullNotify(observations []models.BackObservation) {
var regions []string
for _, observation := range observations {
regions = append(regions, observation.Region)
}
regions = utils.Distinct(regions)
notification := models.BackNotification{Time: time.Now(), Kind: "疫情", Content: "出现了新的接触者,请及时登录系统进行处理"}
sendInfo := models.SendInfo{Region: regions, Channel: []int{0, 1}, Notification: notification}
notify.SendNotify(sendInfo)
}
//updateObservationRegion send notify while update observation's region
func updateObservationRegion(region string) {
// Add to notify
// Send email to the target region amdin
notification := models.BackNotification{Time: time.Now(), Kind: "疫情", Content: "本地有新的接触者,请及时登录系统进行处理"}
sendInfo := models.SendInfo{Region: []string{region}, Channel: []int{0, 1}, Notification: notification}
notify.SendNotify(sendInfo)
}
func updateWhileDiagnosis(claims models.TokenClaims, patientId int) {
// Update sub contact to contact and nomeasure
// Add to notify
//updateSituation make some special resolve while situation update
func updateSituation(claims models.TokenClaims, oldObservationMap, newObservationMap map[string]interface{}) {
if newObservationMap["health_situation"] != nil {
newHealthSituation := int(newObservationMap["health_situation"].(float64))
oldHealthSituation := oldObservationMap["health_situation"].(int)
// Update health situation change time and measure_situation
if newHealthSituation != oldHealthSituation {
newObservationMap["health_change_time"] = time.Now()
newObservationMap["measure_situation"] = 0
}
// Deal with contact to patient
if oldHealthSituation == 2 && newHealthSituation == 1 {
// Query sub contacts
queryMap := []map[string]interface{}{{"contact_person": oldObservationMap["id"].(int)}}
subContacts := models.ListField[models.BackObservation](queryMap, false, "id", "region")
// Get reginos and assemble situation record
var regions []string
var subContactRecords []models.BackSituationRecord
for _, subContact := range *subContacts {
regions = append(regions, subContact["region"].(string))
subContactRecord := models.BackSituationRecord{
Observation: int(newObservationMap["id"].(float64)),
Record: record___20(),
}
subContactRecords = append(subContactRecords, subContactRecord)
}
// Update sub contact
updateMap := map[string]interface{}{
"health_situation": 2,
"health_change_time": newObservationMap["health_change_time"],
"measure_situation": 0,
}
models.Update[models.BackObservation](queryMap, updateMap)
// Insert subContacts' record
var recordJMaps []map[string]interface{}
utils.Strcut2Map(subContactRecords, &recordJMaps)
recordCMap := models.MapsJ2c[models.BackSituationRecord](recordJMaps, true)
models.BeforeBatchSave(&recordCMap, claims.ID)
models.BatchInsert[models.BackSituationRecord](recordCMap)
// Send nofity
regions = utils.Distinct(regions)
notification := models.BackNotification{
Time: newObservationMap["health_change_time"].(time.Time),
Kind: "疫情",
Content: "由于密接者转为患者,次密接者状态需要修改",
}
sendInfo := models.SendInfo{
Region: regions,
Channel: []int{0, 1},
Notification: notification,
}
notify.SendNotify(sendInfo)
}
insertSituationRecord(claims, oldObservationMap, newObservationMap)
}
}
//insertSituationRecord insert situation record
func insertSituationRecord(claims models.TokenClaims, oldObservation, newObservation map[string]interface{}) bool {
var oldSituation, newSituation string
if oldObservation["id"] == nil {
@@ -154,20 +318,22 @@ func insertSituationRecord(claims models.TokenClaims, oldObservation, newObserva
switch situationConvert {
case "00_10":
recordContent = record00_10()
case "00_20":
recordContent = record00_20()
case "00_30":
recordContent = record00_30()
case "00_12":
recordContent = record00_12(newObservation["region"].(string), newObservation["address"].(string))
case "10_12":
recordContent = record10_12(newObservation["region"].(string), newObservation["address"].(string))
case "00_20", "33_20", "34_20":
recordContent = record___20()
case "12_01", "23_01", "24_01", "33_01", "34_01":
recordContent = record___01()
case "20_23", "30_33", "24_23", "34_33":
recordContent = record____3(newObservation["region"].(string), newObservation["address"].(string))
case "20_24", "30_34", "23_24", "33_34":
recordContent = record____4(newObservation["region"].(string), newObservation["address"].(string))
case "23_10", "24_10", "33_10", "34_10":
recordContent = record___10()
default:
if oldSituation != "00" {
models.Upsert[models.BackObservation](oldObservation)
@@ -193,7 +359,7 @@ func record00_12(region, address string) string {
date := utils.FormatDate(time.Now())
return fmt.Sprintf("%s 于 %s %s 确诊为患者", date, region, address)
}
func record00_20() string {
func record___20() string {
date := utils.FormatDate(time.Now())
return date + " 转为密接"
}

10
service/management/pcr.go Normal file
View File

@@ -0,0 +1,10 @@
package management
import "nCovTrack-Backend/models"
func InsertPcr(claims models.TokenClaims, jsonMap map[string]interface{}) bool {
colMap := models.MapJ2c[models.BackPcr](jsonMap, true)
models.BeforeSave(colMap, claims.ID)
ok, rowsAffected := models.Upsert[models.BackPcr](colMap)
return ok && rowsAffected != 0
}

View File

@@ -4,35 +4,65 @@ import (
"encoding/json"
"nCovTrack-Backend/global"
"nCovTrack-Backend/models"
"strconv"
"nCovTrack-Backend/utils"
)
type NotifyFunc func([]string, models.BackNotification)
const (
NOTIFY_KEY = "notification_"
NOTIFY_DEL_VALUE = "notify_del"
)
func InsertNotification(userId int, notification models.BackNotification) {
key := NOTIFY_KEY + strconv.Itoa(userId)
valueStr, _ := json.Marshal(notification)
global.Redis.RPush(key, valueStr)
var (
NOTIFY_CHANNEL_FUNC_ARR = []NotifyFunc{notifyNotification, emailNotification}
)
//emailNotification send email
func emailNotification(regions []string, notification models.BackNotification) {
queryMap := []map[string]interface{}{{"region": regions, "role": global.ROLE_ID_MAP["ADMIN"]}}
observations := models.ListField[models.BackUser](queryMap, false, "email")
var emails []string
for _, observation := range *observations {
emails = append(emails, observation["email"].(string))
}
utils.SendEmail(notification.Kind+"通知邮件", notification.Content, emails...)
}
func DeleteNotification(userId int, index int) {
key := NOTIFY_KEY + strconv.Itoa(userId)
//notifyNotification add to notify system
func notifyNotification(regions []string, notification models.BackNotification) {
valueByte, _ := json.Marshal(notification)
pipe := global.Redis.TxPipeline()
for _, region := range regions {
pipe.RPush(NOTIFY_KEY+region, valueByte)
}
pipe.Exec()
}
//DeleteNotification delete notify by id
func DeleteNotification(region string, index int) {
key := NOTIFY_KEY + region
pipe := global.Redis.TxPipeline()
pipe.LSet(key, int64(index), NOTIFY_DEL_VALUE)
pipe.LRem(key, 2, NOTIFY_DEL_VALUE)
pipe.Exec()
}
func QueryNotificationLen(userId int) int {
key := NOTIFY_KEY + strconv.Itoa(userId)
//CleanNotification delete all notify
func CleanNotification(region string) {
key := NOTIFY_KEY + region
global.Redis.Del(key)
}
//QueryNotificationLen query the count notification
func QueryNotificationLen(region string) int {
key := NOTIFY_KEY + region
return int(global.Redis.LLen(key).Val())
}
func ListNotifycation(userId int, start, end int) []models.BackNotification {
key := NOTIFY_KEY + strconv.Itoa(userId)
//ListNotifycation list the notifications ny range
func ListNotifycation(region string, start, end int) []models.BackNotification {
key := NOTIFY_KEY + region
var notifications []models.BackNotification
notificationStrArr := global.Redis.LRange(key, int64(start), int64(end)).Val()
for _, notificationStr := range notificationStrArr {
@@ -42,3 +72,18 @@ func ListNotifycation(userId int, start, end int) []models.BackNotification {
}
return notifications
}
//SendNotify send notify to kafka
func SendNotify(send models.SendInfo) {
sendInfo, _ := json.Marshal(send)
global.KafkaProducerChan <- sendInfo
}
//HandleKafkaNotify handle kafka info
func HandleKafkaNotify(sendInfoByte []byte) {
var sendInfo models.SendInfo
json.Unmarshal(sendInfoByte, &sendInfo)
for _, channel := range sendInfo.Channel {
NOTIFY_CHANNEL_FUNC_ARR[channel](sendInfo.Region, sendInfo.Notification)
}
}

View File

@@ -2,13 +2,15 @@ package user
import (
"fmt"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"nCovTrack-Backend/global"
"nCovTrack-Backend/models"
"nCovTrack-Backend/service/notify"
"nCovTrack-Backend/utils"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
)
const (
@@ -50,6 +52,15 @@ func Register(user map[string]interface{}) bool {
user["approver"] = 0
colMap := models.MapJ2c[models.BackUser](user, false)
ok, rowsAffected := models.Upsert[models.BackUser](colMap)
var sendRegion string
if int(user["role"].(float64)) == global.ROLE_ID_MAP["ADMIN"] {
sendRegion = strings.Split(user["region"].(string), " ")[0]
} else {
sendRegion = user["region"].(string)
}
notification := models.BackNotification{Time: time.Now(), Kind: "审批", Content: "有新的注册待审批"}
sendInfo := models.SendInfo{Region: []string{sendRegion}, Channel: []int{0}, Notification: notification}
notify.SendNotify(sendInfo)
if !ok || rowsAffected == 0 {
return false
}
@@ -95,7 +106,7 @@ func ApproveRegister(claims models.TokenClaims, email string, pass bool) bool {
} else {
approver = -claims.ID
}
updateMap := map[string]interface{}{"approver": approver}
updateMap := map[string]interface{}{"approver": approver, "modify_time": time.Now()}
ok, rowsAffected := models.Update[models.BackUser](queryMap, updateMap)
if !ok || rowsAffected == 0 {
return false
@@ -111,11 +122,12 @@ func ChangePassword(changePwd map[string]interface{}) bool {
}
newPassword := utils.PasswordEncrypt(changePwd["newPassword"].(string))
colMap := map[string]interface{}{
"id": 1,
"id": 1.0,
"password": newPassword,
}
models.BeforeSave(colMap, -1)
delete(colMap, "id")
delete(colMap, "modify_user")
rowAffected := global.Db.Model(models.BackUser{}).Where("email = ?", changePwd["email"]).Updates(colMap).RowsAffected
if rowAffected == 0 {
return false