feat: management && notify

This commit is contained in:
fallen-angle
2022-05-04 20:06:21 +08:00
parent e58bafd0d3
commit 7598280fc1
28 changed files with 1226 additions and 143 deletions

View File

@@ -1,46 +0,0 @@
package investigate
import (
"encoding/json"
"nCovTrack-Backend/global"
"nCovTrack-Backend/models"
"nCovTrack-Backend/utils"
)
func fakerGetRequest(uri string) string {
resStr := utils.GetWhioutHeader(global.FACKER_HOST + uri)
var res utils.GinResponse
_ = json.Unmarshal([]byte(resStr), &res)
dataStr, _ := json.Marshal(res.Data)
return string(dataStr)
}
func QueryHotelContacts() []models.HotelContactRequest {
dataStr := fakerGetRequest("query/contacts/hotel/320581199103182689")
var data []models.HotelContactRequest
err := json.Unmarshal([]byte(dataStr), &data)
if err != nil {
panic(err)
}
return data
}
func QueryRailwayContacts() []models.RailwayContactRequest {
dataStr := fakerGetRequest("query/contacts/railway/320581199103182689")
var data []models.RailwayContactRequest
err := json.Unmarshal([]byte(dataStr), &data)
if err != nil {
panic(err)
}
return data
}
func QueryPatients() []models.PatientRequest {
dataStr := fakerGetRequest("query/contacts/railway/320581199103182689")
var data []models.PatientRequest
err := json.Unmarshal([]byte(dataStr), &data)
if err != nil {
panic(err)
}
return data
}

View File

@@ -1 +0,0 @@
package investigate

104
service/management/faker.go Normal file
View File

@@ -0,0 +1,104 @@
package management
import (
"encoding/json"
"fmt"
"nCovTrack-Backend/global"
"nCovTrack-Backend/models"
"nCovTrack-Backend/utils"
"strings"
"time"
)
func fakerGetRequest(uri string) string {
resStr := utils.GetWhioutHeader(global.FACKER_HOST + uri)
var res utils.GinResponse
_ = json.Unmarshal([]byte(resStr), &res)
dataStr, _ := json.Marshal(res.Data)
return string(dataStr)
}
func queryHotelContacts(identification string) []models.HotelContactRequest {
dataStr := fakerGetRequest("query/contacts/hotel/" + identification)
var data []models.HotelContactRequest
err := json.Unmarshal([]byte(dataStr), &data)
if err != nil {
panic(err)
}
return data
}
func queryRailwayContacts(identification string) []models.RailwayContactRequest {
dataStr := fakerGetRequest("query/contacts/railway/" + identification)
var data []models.RailwayContactRequest
err := json.Unmarshal([]byte(dataStr), &data)
if err != nil {
panic(err)
}
return data
}
func queryPatients(identification string) []models.PatientRequest {
dataStr := fakerGetRequest("query/contacts/railway/" + identification)
var data []models.PatientRequest
err := json.Unmarshal([]byte(dataStr), &data)
if err != nil {
panic(err)
}
return data
}
func queryContacts(identification string) []models.BackObservation {
hotelContacts := queryHotelContacts(identification)
railwayContacts := queryRailwayContacts(identification)
observations := append(fakerContacts2Observations(hotelContacts), fakerContacts2Observations(railwayContacts)...)
return observations
}
func splitFakerAddress(fakerAddress string) string {
addresses := strings.Split(fakerAddress, " ")
return addresses[1] + " " + addresses[2]
}
func fakerContacts2Observations(contacts any) []models.BackObservation {
var observations []models.BackObservation
switch contacts.(type) {
case []models.HotelContactRequest:
for _, contact := range contacts.([]models.HotelContactRequest) {
tranjectory := fmt.Sprintf("在%s-%s期间与患者同期留宿%s", contact.InData.String(), contact.OutData.String(), contact.HotelName)
observation := &models.BackObservation{
Name: contact.Name,
Age: contact.Age,
Sex: contact.Sex,
Phone: contact.Phone,
Identification: contact.Identification,
Region: splitFakerAddress(contact.Address),
Address: "",
HealthSituation: global.HEALTH_SITUATION_ID_MAP["CONTACT"],
HealthChangeTime: time.Now(),
MeasureSituation: global.MEASURE_SITUATION_ID_MAP["NOMEASURE"],
Trajectory: tranjectory,
}
observations = append(observations, *observation)
}
case []models.RailwayContactRequest:
for _, contact := range contacts.([]models.RailwayContactRequest) {
tranjectory := fmt.Sprintf("在%s与患者同期乘坐%s", contact.Launch.String(), contact.Train)
observation := &models.BackObservation{
Name: contact.Name,
Age: contact.Age,
Sex: contact.Sex,
Phone: contact.Phone,
Identification: contact.Identification,
Region: splitFakerAddress(contact.Address),
Address: "",
HealthSituation: global.HEALTH_SITUATION_ID_MAP["CONTACT"],
HealthChangeTime: time.Now(),
MeasureSituation: global.MEASURE_SITUATION_ID_MAP["NOMEASURE"],
Trajectory: tranjectory,
}
observations = append(observations, *observation)
}
}
return observations
}

View File

@@ -0,0 +1,22 @@
package management
import (
"nCovTrack-Backend/models"
)
func InsertLocation(claims models.TokenClaims, locationJMap map[string]interface{}) bool {
locationCMap := models.MapJ2c[models.BackLocation](locationJMap, true)
models.BeforeSave(locationCMap, claims.ID)
ok, rowsAffected := models.Upsert[models.BackLocation](locationCMap)
return (ok && rowsAffected != 0)
}
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")
}
func DeleteLocation(id int) bool {
ok, rowsAffected := models.DeleteById[models.BackLocation](id)
return (ok && rowsAffected != 0)
}

View File

@@ -0,0 +1,223 @@
package management
import (
"fmt"
"nCovTrack-Backend/global"
"nCovTrack-Backend/models"
"nCovTrack-Backend/utils"
"time"
)
func PullFromFaker(claims models.TokenClaims, patientId int) int64 {
// Get patient's identification by id
queryMap := []map[string]interface{}{{"id": patientId}}
patient := models.GetField[models.BackObservation](queryMap, false, "identification")
if patient == nil || patient["identification"] == nil {
return -1
}
// Pull contacts form faker
observations := queryContacts(patient["identification"].(string))
// Set ContactPerson
for i := range observations {
observations[i].ContactPerson = patientId
}
// Insert into db
var observationsJMap []map[string]interface{}
utils.Strcut2Map(observations, &observationsJMap)
observationsCMap := models.MapsJ2c[models.BackObservation](observationsJMap, false)
models.BeforeBatchSave(&observationsCMap, claims.ID)
_, rowsAffected := models.BatchInsert[models.BackObservation](observationsCMap)
// Generate situation record
if rowsAffected != 0 {
pullSituationRecord(claims, observations)
}
return rowsAffected
}
func ListObservation(jsonMap map[string]interface{}) []models.ListObeservation {
colMap := models.MapJ2c[models.BackObservation](jsonMap, true)
queryMap := []map[string]interface{}{colMap}
return listObservation(queryMap)
}
func GetObservation(id int) map[string]interface{} {
observationCMap := models.GetField[models.BackObservation]([]map[string]interface{}{{"id": id}}, true, "is_delete")
observationJMap := models.MapC2j[models.BackObservation](observationCMap, true)
pcrRecordCMap := models.ListField[models.BackPcr]([]map[string]interface{}{{"observation": id}}, true, "is_delete")
pcrRecordJMap := models.MapsC2j[models.BackPcr](*pcrRecordCMap, true)
situationRecordCMap := models.ListField[models.BackSituationRecord]([]map[string]interface{}{{"observation": id}}, true, "is_delete")
situationRecordJMap := models.MapsC2j[models.BackSituationRecord](*situationRecordCMap, true)
observationJMap["pcrRecord"] = pcrRecordJMap
observationJMap["situationRecord"] = situationRecordJMap
return observationJMap
}
func InsertObservation(claims models.TokenClaims, jsonMap map[string]interface{}) bool {
colMap := models.MapJ2c[models.BackObservation](jsonMap, true)
models.BeforeSave(colMap, claims.ID)
ok, rowsAffected := models.Upsert[models.BackObservation](colMap)
queryMap := []map[string]interface{}{{"identification": jsonMap["identification"]}}
// Get result after insert, assemble record will use it.
newObservation := models.GetField[models.BackObservation](queryMap, true)
recordOk := insertSituationRecord(claims, map[string]interface{}{}, newObservation)
return (ok && recordOk && rowsAffected != 0)
}
func UpdateObservation(claims models.TokenClaims, jsonMap map[string]any) bool {
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
}
// 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
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").
Joins("LEFT JOIN back_pcr ON back_observation.id = back_pcr.observation").
Joins("LEFT JOIN back_situation_record ON back_observation.id = back_situation_record.observation")
for _, query := range queryMap {
query["is_delete"] = 0
// Add the table prefix
fullQuery := map[string]interface{}{}
for k := range query {
fullQuery["back_observation."+k] = query[k]
}
tx = tx.Or(fullQuery)
}
tx.Find(&observations)
return observations
}
func pullSituationRecord(claims models.TokenClaims, observations []models.BackObservation) {
// Query observations' id
var identifications []string
for _, observation := range observations {
identifications = append(identifications, observation.Identification)
}
queryMap := []map[string]interface{}{{"identification": identifications}}
observationMaps := models.ListField[models.BackObservation](queryMap, false, "id", "identification")
// Assemble records
var records []models.BackSituationRecord
recordContent := record00_20()
for _, observationMap := range *observationMaps {
record := models.BackSituationRecord{Observation: observationMap["id"].(int), Record: recordContent}
records = append(records, record)
}
// Insert into db
var recordsJMaps []map[string]interface{}
utils.Strcut2Map(records, &recordsJMaps)
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
}
func updateObservationRegion(region string) {
// Add to notify
// Send email to the target region amdin
}
func updateWhileDiagnosis(claims models.TokenClaims, patientId int) {
// Update sub contact to contact and nomeasure
// Add to notify
}
func insertSituationRecord(claims models.TokenClaims, oldObservation, newObservation map[string]interface{}) bool {
var oldSituation, newSituation string
if oldObservation["id"] == nil {
// insert observation
oldSituation = "00"
} else {
// update observation
oldSituation = fmt.Sprintf("%d%d", oldObservation["health_situation"], oldObservation["measure_situation"])
}
if newObservation["health_situation"] == nil || newObservation["measure_situation"] == nil {
// Situation not update
return true
}
newSituation = fmt.Sprintf("%d%d", newObservation["health_situation"], newObservation["measure_situation"])
// Situation not update
if oldSituation == newSituation {
return true
}
// Set record content accrodding the situation convertions
var recordContent string
situationConvert := oldSituation + "_" + newSituation
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 "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))
default:
if oldSituation != "00" {
models.Upsert[models.BackObservation](oldObservation)
} else {
models.DropById[models.BackObservation](newObservation["id"].(int))
}
return false
}
record := models.BackSituationRecord{Observation: newObservation["id"].(int), Record: recordContent}
var recordJMap map[string]interface{}
utils.Strcut2Map(record, &recordJMap)
recordCMap := models.MapJ2c[models.BackSituationRecord](recordJMap, true)
models.BeforeSave(recordCMap, claims.ID)
models.Upsert[models.BackSituationRecord](recordCMap)
return true
}
func record00_10() string {
date := utils.FormatDate(time.Now())
return date + " 确诊为患者"
}
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 {
date := utils.FormatDate(time.Now())
return date + " 转为密接"
}
func record00_30() string {
date := utils.FormatDate(time.Now())
return date + " 转为次密接"
}
func record___01() string {
date := utils.FormatDate(time.Now())
return fmt.Sprintf("%s 解除风险", date)
}
func record10_12(region, address string) string {
date := utils.FormatDate(time.Now())
return fmt.Sprintf("%s 转至医院:%s %s", date, region, address)
}
func record___10() string {
date := utils.FormatDate(time.Now())
return date + " 确诊为患者"
}
func record____3(region, address string) string {
date := utils.FormatDate(time.Now())
return fmt.Sprintf("%s 集中隔离至:%s %s", date, region, address)
}
func record____4(region, address string) string {
date := utils.FormatDate(time.Now())
return fmt.Sprintf("%s 进行居家隔离:%s %s", date, region, address)
}

44
service/notify/notify.go Normal file
View File

@@ -0,0 +1,44 @@
package notify
import (
"encoding/json"
"nCovTrack-Backend/global"
"nCovTrack-Backend/models"
"strconv"
)
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)
}
func DeleteNotification(userId int, index int) {
key := NOTIFY_KEY + strconv.Itoa(userId)
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)
return int(global.Redis.LLen(key).Val())
}
func ListNotifycation(userId int, start, end int) []models.BackNotification {
key := NOTIFY_KEY + strconv.Itoa(userId)
var notifications []models.BackNotification
notificationStrArr := global.Redis.LRange(key, int64(start), int64(end)).Val()
for _, notificationStr := range notificationStrArr {
var notification models.BackNotification
json.Unmarshal([]byte(notificationStr), &notification)
notifications = append(notifications, notification)
}
return notifications
}

View File

@@ -27,11 +27,13 @@ const (
rds_CITY_LEVEL_TOTAL_CONFIRM_KEY = "cityLevelTotalConfirm"
rds_LAST_UPDATE_TIME = "statisticsLastUpdateTime"
rds_LAST_CACHE_TIME = "statisticsLastCacheTime"
rds_CHINA_DAY_ADD_LIST_KEY = "chinaDayAdd"
rds_CHINA_DAY_LIST_KEY = "chinaDay"
SORT_TODAY_CONFIRM = "today"
SORT_TOTAL_CONFIRM = "total"
SORT_NOW_CONFIRM = "now"
D
json_FOREIGN_COUNTRY = "境外"
json_FOREIGN_CITY = "外地"
json_TO_BE_CONFIRM = "待确认"
@@ -54,6 +56,22 @@ func cacheNCovStatistics() {
cacheChinaInfo(nCovResData)
cacheLevelInfo(nCovResData)
cacheLastUpdateTime(nCovResData)
resp = utils.GetWhioutHeader(global.CHINA_NCOV_STATISTIC_TREND_URL)
}
func CacheNCovTrend() {
resp := utils.GetWhioutHeader(global.CHINA_NCOV_STATISTIC_TREND_URL)
var nCovRes map[string]interface{}
json.Unmarshal([]byte(resp), &nCovRes)
nCovResData := nCovRes["data"].(map[string]interface{})
cacheChinaTrend(nCovResData)
}
func cacheChinaTrend(data map[string]interface{}) {
chinaDayAdd, _ := json.Marshal(data["chinaDayAddList"])
chinaDay, _ := json.Marshal(data["chinaDayList"])
global.Redis.Set(rds_CHINA_DAY_ADD_LIST_KEY, chinaDayAdd, 0)
global.Redis.Set(rds_CHINA_DAY_LIST_KEY, chinaDay, 0)
}
func cacheChinaInfo(data map[string]interface{}) {

View File

@@ -51,6 +51,32 @@ func GetChinaNCovStatistic() models.ChinaData {
return data
}
func GetChinaDayAdd() []models.ChinaDayAdd {
chinaDayAddStr := global.Redis.Get(rds_CHINA_DAY_ADD_LIST_KEY).Val()
if chinaDayAddStr == "" {
CacheNCovTrend()
chinaDayAddStr = global.Redis.Get(rds_CHINA_DAY_ADD_LIST_KEY).Val()
}
var chinaDayAddList []models.ChinaDayAdd
json.Unmarshal([]byte(chinaDayAddStr), &chinaDayAddList)
return chinaDayAddList
}
func GetChinaDay() []models.ChinaDay {
chinaDayStr := global.Redis.Get(rds_CHINA_DAY_LIST_KEY).Val()
if chinaDayStr == "" {
CacheNCovTrend()
chinaDayStr = global.Redis.Get(rds_CHINA_DAY_LIST_KEY).Val()
}
var chinaDayList []models.ChinaDay
json.Unmarshal([]byte(chinaDayStr), &chinaDayList)
return chinaDayList
}
func GetChinaTrend() models.ChinaTrend {
return models.ChinaTrend{ChinaDayAddList: GetChinaDayAdd(), ChinaDayList: GetChinaDay()}
}
func getEntireRedisList(key string) []interface{} {
var data []interface{}
dataStrArr := global.Redis.LRange(key, 0, -1).Val()

View File

@@ -17,7 +17,6 @@ const (
// Login if login success, will return token
func Login(user map[string]interface{}) (token string) {
// TODO: need to detect is passed or not
account := user["account"].(string)
var queryMap []map[string]interface{}
if strings.Contains(account, "@") {