From b1d7efd8c4ab9c4bf56f62e636a358a5182c09bf Mon Sep 17 00:00:00 2001 From: zhangzengfei <zhangzengfei@smartai.com> Date: 星期六, 28 九月 2024 23:43:58 +0800 Subject: [PATCH] fix db colummn --- db/repository.go | 318 ------------------ db/device.go | 35 ++ db/moveInOut.go | 77 ++++ db/label.go | 29 + rule/service.go | 6 db/personStatusRule.go | 27 + db/personLabel.go | 73 ++++ .idea/workspace.xml | 14 db/person.go | 46 ++ db/database.go | 9 db/task.go | 30 + db/models.go | 154 -------- db/publicHouse.go | 27 + rule/engine.go | 24 db/summary.go | 117 ++++++ 15 files changed, 507 insertions(+), 479 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index d901054..6521436 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,7 +2,12 @@ <project version="4"> <component name="ChangeListManager"> <list default="true" id="919111b8-f2aa-4154-8db0-88e76c9af55d" name="Default Changelist" comment=""> - <change beforePath="$PROJECT_DIR$/cache/device.go" beforeDir="false" afterPath="$PROJECT_DIR$/cache/device.go" afterDir="false" /> + <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> + <change beforePath="$PROJECT_DIR$/db/database.go" beforeDir="false" afterPath="$PROJECT_DIR$/db/database.go" afterDir="false" /> + <change beforePath="$PROJECT_DIR$/db/models.go" beforeDir="false" afterPath="$PROJECT_DIR$/db/models.go" afterDir="false" /> + <change beforePath="$PROJECT_DIR$/db/repository.go" beforeDir="false" afterPath="$PROJECT_DIR$/db/repository.go" afterDir="false" /> + <change beforePath="$PROJECT_DIR$/rule/engine.go" beforeDir="false" afterPath="$PROJECT_DIR$/rule/engine.go" afterDir="false" /> + <change beforePath="$PROJECT_DIR$/rule/service.go" beforeDir="false" afterPath="$PROJECT_DIR$/rule/service.go" afterDir="false" /> </list> <option name="SHOW_DIALOG" value="false" /> <option name="HIGHLIGHT_CONFLICTS" value="true" /> @@ -192,12 +197,13 @@ <property name="settings.editor.selected.configurable" value="watcher.settings" /> </component> <component name="RecentsManager"> - <key name="MoveFile.RECENT_KEYS"> - <recent name="F:\workspace\golang\cloud_ai\ruleModelEngine\cache" /> - </key> <key name="CopyFile.RECENT_KEYS"> <recent name="F:\workspace\golang\cloud_ai\ruleModelEngine" /> </key> + <key name="MoveFile.RECENT_KEYS"> + <recent name="E:\Basic\ruleModelEngine\db" /> + <recent name="F:\workspace\golang\cloud_ai\ruleModelEngine\cache" /> + </key> </component> <component name="RunManager" selected="Go Build.go build main.go"> <configuration name="go build elastic.go" type="GoApplicationRunConfiguration" factoryName="Go Application" temporary="true" nameIsGenerated="true"> diff --git a/db/database.go b/db/database.go index 43ef00e..ccbb054 100644 --- a/db/database.go +++ b/db/database.go @@ -1,10 +1,11 @@ package db import ( + "time" + "gorm.io/driver/mysql" "gorm.io/gorm" "ruleModelEngine/config" - "time" ) var DB *gorm.DB @@ -35,7 +36,11 @@ sqlDb.SetConnMaxLifetime(time.Duration(120) * time.Second) sqlDb.SetConnMaxIdleTime(time.Duration(1800) * time.Second) - db.AutoMigrate(&PublicHouse{}) + db.AutoMigrate( + &PublicHouse{}, + &PersonnelStatusRule{}, + &Task{}, + ) DB = db return nil diff --git a/db/device.go b/db/device.go new file mode 100644 index 0000000..b2881fb --- /dev/null +++ b/db/device.go @@ -0,0 +1,35 @@ +package db + +type Device struct { + DeviceCode string `gorm:"column:device_code"` // 璁惧缂栫爜 + Name string `gorm:"column:name"` // 璁惧鍚嶇О + Longitude string `gorm:"column:longitude"` // 缁忓害 + Latitude string `gorm:"column:latitude"` // 绾害 + CaptureNum int `gorm:"column:capture_num"` // 鎶撴媿娆℃暟 + Building string `gorm:"column:building"` // 妤煎彿 + BuildingType BuildingType `gorm:"column:building_type"` // 妤煎彿 + Unit string `gorm:"column:unit"` // 鍗曞厓鍙� + Position string `gorm:"column:position"` // 瀹夎浣嶇疆 + Floor string `gorm:"column:floor"` // 妤煎眰鍙� + Type int `gorm:"column:type"` // 璁惧绫诲瀷: 0 鎽勫儚鏈�, 1 璁惧绠� + Scene int `gorm:"column:scene"` // 瀹夎鍦烘櫙: 0 瀹ゅ唴, 1 瀹ゅ + Direction string `gorm:"column:direction"` // 鎷嶆憚鏂瑰悜: in, out + Entrance string `gorm:"column:entrance"` // 鍏ュ彛鐨勪綅缃�: "1F,-1F,-2F" + CommunityID string `gorm:"column:community_id"` // 甯搁┗灏忓尯 domain unit ID + OrgID string `gorm:"column:org_id"` // 鎵�灞炴淳鍑烘墍 domain unit ID + MaxBuildingFloor int `gorm:"column:max_building_floor"` //鏈�楂樻ゼ灞傚彿 + MinBuildingFloor int `gorm:"column:min_building_floor"` //鏈�浣庢ゼ灞傚彿 + Disabled int `gorm:"column:disabled"` // 绂佺敤 +} + +// 鏌ヨ璁惧琛� +func GetDeviceData() ([]Device, error) { + // 鏌ヨ鏁版嵁 + var db = DB + var device []Device + result := db.Table("device").Where("community_id != ?", "").Find(&device) + if result.Error != nil { + return nil, result.Error + } + return device, nil +} diff --git a/db/label.go b/db/label.go new file mode 100644 index 0000000..ac87efc --- /dev/null +++ b/db/label.go @@ -0,0 +1,29 @@ +package db + +type LabelManage struct { + ID string `gorm:"column:id"` + Name string `gorm:"column:name"` + Comment string `gorm:"column:comment"` + Type int `gorm:"column:type"` + ValidDays int `gorm:"column:valid_days"` +} + +func (LabelManage) TableName() string { + return "label" +} + +// 鏌ヨ浜虹墿韬唤灞炴�ц〃 +func GeIdentityLabels() ([]LabelManage, error) { + var db = DB + + // 鏌ヨ鏁版嵁 + var labelManageIdentity []LabelManage + if err := db.Table("label"). + Select("id, name, valid_days"). + Where("type = 2"). + Find(&labelManageIdentity).Error; err != nil { + return nil, err + } + + return labelManageIdentity, nil +} diff --git a/db/models.go b/db/models.go index 67af5ca..52eef2e 100644 --- a/db/models.go +++ b/db/models.go @@ -1,18 +1,21 @@ package db -import ( - "time" +type BuildingType int + +const ( + BuildingTypeResidential BuildingType = 1 //浣忓畢妤� + BuildingTypeMixedUse BuildingType = 2 //鍟嗕綇妤� + BuildingTypePublicRental BuildingType = 3 //鍏鎴� + BuildingTypeLowIncome BuildingType = 4 //寤夌鎴� + BuildingTypeOldResidential BuildingType = 5 //鑰佹棫灏忓尯 + BuildingTypeOffice BuildingType = 6 //鍐欏瓧妤� ) -type PersonnelStatusRule struct { - ID int `gorm:"column:id"` - Name string `gorm:"column:name"` - DetectionCountStart int `gorm:"column:detectionCountStart"` - DetectionCountEnd int `gorm:"column:detectionCountEnd"` - DetectionDaysStart int `gorm:"column:detectionDaysStart"` - DetectionDaysEnd int `gorm:"column:detectionDaysEnd"` - Status string `gorm:"column:status"` -} +const ( + StatusStranger int = 1 + StatusVisitor int = 2 + StatusResident int = 3 +) type AlarmRule struct { RuleId string `json:"ruleId"` @@ -29,120 +32,6 @@ TargetType string `json:"targetType"` Floor string `json:"floor"` } - -type BuildingType int - -const ( - BuildingTypeResidential BuildingType = 1 //浣忓畢妤� - BuildingTypeMixedUse BuildingType = 2 //鍟嗕綇妤� - BuildingTypePublicRental BuildingType = 3 //鍏鎴� - BuildingTypeLowIncome BuildingType = 4 //寤夌鎴� - BuildingTypeOldResidential BuildingType = 5 //鑰佹棫灏忓尯 - BuildingTypeOffice BuildingType = 6 //鍐欏瓧妤� -) - -//type status int - -const ( - StatusStranger int = 1 - StatusVisitor int = 2 - StatusResident int = 3 -) - -type Device struct { - DeviceCode string `gorm:"column:deviceCode" json:"deviceCode" example:"J83762"` //璁惧缂栫爜 - AreaID string `json:"areaID" gorm:"index;column:communityID;type:varchar(299);"` //甯镐綇灏忓尯 domain unit ID - BuildingType BuildingType `gorm:"column:building_type;type:tinyint(1);not null;default:0" json:"buildingType"` //妤煎畤绫诲瀷 - MaxBuildingFloor int `gorm:"column:max_building_floor;type:tinyint(1);not null;default:0" json:"maxBuildingFloor"` //鏈�楂樻ゼ灞傚彿 -} - -type Task struct { - Id int `gorm:"column:id"` - Name string `gorm:"name"` -} - -func (Task) TableName() string { - return "task" -} - -type MoveInout struct { - //RecordId int `gorm:"column:record_id"` - DocumentNumber string `gorm:"column:document_number"` - CommunityID string `gorm:"column:community_id"` - MoveInDate time.Time `gorm:"column:move_in_date"` - MoveOutDate *time.Time `gorm:"column:move_out_date"` - Status string `gorm:"column:status"` - MoveType string `gorm:"column:move_type"` -} - -func (MoveInout) TableName() string { - return "move_inout" -} - -type Resident struct { - CommunityId string `gorm:"column:community_id"` - DocumentNumber string `gorm:"column:document_number"` - LastAppearanceTime int64 `gorm:"column:last_appearance_time"` - CreateAt string `gorm:"column:create_at"` -} - -type PersonStatus struct { - Id uint `gorm:"column:id;primary_key;auto_increment;not null;"` - OrgId string `gorm:"column:org_id;type:varchar(299);not null;default:''"` // 娲惧嚭鎵�id - CommunityID string `gorm:"uniqueIndex:idx_document_number_community_id;index:community_id_last_appearance_time;column:community_id;type:varchar(299);not null;default:''"` // 灏忓尯id - DocumentNumber string `gorm:"uniqueIndex:idx_document_number_community_id;column:document_number;type:varchar(299);not null;default:''"` // 妗f缂栧彿 - DaysAppeared int `gorm:"column:days_appeared;type:int(11);not null;default:0" json:"daysAppeared"` // 鍑虹幇澶╂暟 - Count int `gorm:"column:count;type:int;not null;default:0"` // 鎶撴媿娆℃暟 - Status string `gorm:"column:status;type:varchar(255);not null;default:''"` //鏍囩 - LastAppearanceTime int64 `gorm:"index:community_id_last_appearance_time;column:last_appearance_time;type:int;not null;default:0" json:"lastAppearanceTime"` //鏈�鍚庡嚭鐜版椂闂� - LastAppearanceStatusTime int64 `gorm:"column:last_appearance_status_time"` - LastLocation string `gorm:"column:last_location;type:varchar(255);not null;default:''" json:"lastLocation"` //鏈�鍚庡嚭鐜板湴鐐� - FrequentAddress string `gorm:"column:frequent_address;type:varchar(255);not null;default:''" json:"frequentAddress"` //甯稿嚭鐜板湴鐐� - CreatedAt time.Time - UpdatedAt time.Time - NewStatus string `gorm:"-"` - ////OrgId string `gorm:"column:org_id"` - //CommunityID string `gorm:"column:communityID"` - //DocumentNumber string `gorm:"column:documentNumber"` - //Status string `gorm:"column:status"` - //FrequentAddress string `gorm:"column:frequentAddress"` -} - -func (PersonStatus) TableName() string { - return "snapshot_count_summary" -} - -type LabelManage struct { - Id int `gorm:"id"` - Name string `gorm:"name"` - ValidDays int `gorm:"valid_days"` -} - -func (LabelManage) TableName() string { - return "label_manage" -} - -type Identity struct { - CreatedAt time.Time - UpdatedAt time.Time - CommunityID string `gorm:"column:community_id"` - DocumentNumber string `gorm:"column:dbtablepersons_id"` - LabelId int `gorm:"column:label_id"` - ExpireTime int64 `gorm:"column:expire_time"` -} - -func (Identity) TableName() string { - return "dbtablepersons_label" -} - -// -//type ModelMatix struct { -// CommunityID string -// DocumentNumber string -// CaptureDate string -// Status string -// FrequentAddress string -//} type StatusPersonMapping struct { Status string @@ -163,19 +52,4 @@ CaptureDate string `json:"captureDate"` CaptureAddress string `json:"captureAddress"` Direction string `json:"direction"` -} - -type PublicHouse struct { - ID int `gorm:"primaryKey;autoIncrement" json:"id"` // 涓婚敭ID - CommunityID string `gorm:"column:community_id;type:varchar(255)" json:"community_id"` // 灏忓尯ID - Applicant string `gorm:"column:applicant;type:varchar(255)" json:"applicant"` // 鐢宠浜� - IdCard string `gorm:"column:id_card;type:varchar(50)" json:"id_card"` // 璇佷欢缂栧彿 - PhoneNumber string `gorm:"column:phone_number;type:varchar(20)" json:"phone_number"` // 鑱旂郴鐢佃瘽 - Address string `gorm:"column:address;type:varchar(255)" json:"address"` // 鎴垮眿鍦板潃 - ApplicationTime string `gorm:"column:application_time" json:"application_time"` // 鐢宠鏃堕棿 - EndTime string `gorm:"column:end_time" json:"end_time"` // 缁撴潫鏃堕棿 -} - -func (PublicHouse) TableName() string { - return "public_house" } diff --git a/db/moveInOut.go b/db/moveInOut.go new file mode 100644 index 0000000..dfaf544 --- /dev/null +++ b/db/moveInOut.go @@ -0,0 +1,77 @@ +package db + +import ( + "basic.com/valib/logger.git" + "errors" + "gorm.io/gorm" + "time" +) + +type MoveInout struct { + ID string `gorm:"column:id;type:varchar(255);" json:"id"` + OrgId string `gorm:"column:org_id;type:varchar(299);not null;default:''"` // 娲惧嚭鎵�id + CommunityID string `gorm:"uniqueIndex:idx_document_number_community_id;index:community_id_last_appearance_time;column:community_id;type:varchar(299);not null;default:''"` // 灏忓尯id + DocumentNumber string `gorm:"uniqueIndex:idx_document_number_community_id;column:document_number;type:varchar(299);not null;default:''"` //鏈�鍚庡嚭鐜板湴鐐� + MoveInDate string `gorm:"column:move_in_date;type:date;" json:"moveInDate"` //鎼叆鏃ユ湡 + MoveOutDate string `gorm:"column:move_out_date;type:date;" json:"moveOutDate"` //鎼嚭鏃ユ湡 + Status string `gorm:"column:status;"` + MoveType string `gorm:"column:move_type;"` + DaysAppeared int `gorm:"column:days_appeared;type:int(11);not null;default:0" json:"daysAppeared"` // 鍑虹幇澶╂暟 + LastAppearanceTime int64 `gorm:"index:community_id_last_appearance_time;column:last_appearance_time;type:int;not null;default:0" json:"lastAppearanceTime"` //鏈�鍚庡嚭鐜版椂闂� + LastLocation string `gorm:"column:last_location;type:varchar(255);not null;default:''" json:"lastLocation"` //鏈�鍚庡嚭鐜板湴鐐� + CreatedAt time.Time + UpdatedAt time.Time + DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` +} + +// UpdatePersonInfo 鏇存柊鎴栨彃鍏ュ涓汉鍛樹俊鎭� +func UpdateMoveInout(personsMoveInout []MoveInout) error { + var db = DB + // 閬嶅巻浜哄憳淇℃伅 + for _, personMoveInout := range personsMoveInout { + + // 妫�鏌ヨ褰曟槸鍚﹀瓨鍦� + var existingPerson MoveInout + err := db.Where("document_number = ? AND community_id = ?", personMoveInout.DocumentNumber, personMoveInout.CommunityID).First(&existingPerson).Error + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { + logger.Error("Query person error:", err, personMoveInout.DocumentNumber, personMoveInout.CommunityID) + continue + } + + // 濡傛灉璁板綍瀛樺湪锛屽垯鏇存柊 + if existingPerson.DocumentNumber != "" { + //fmt.Println("existingPerson.DocumentNumber: ", existingPerson.DocumentNumber) + if existingPerson.Status != "Verified" { + err := db.Model(&MoveInout{}). + Where("document_number = ? AND community_id = ?", personMoveInout.DocumentNumber, personMoveInout.CommunityID). + Updates(map[string]interface{}{ + "status": personMoveInout.Status, + "move_out_date": personMoveInout.MoveOutDate, + }).Error + if err != nil { + return err + } + } else { + err := db.Model(&MoveInout{}). + Where("document_number = ? AND community_id = ?", personMoveInout.DocumentNumber, personMoveInout.CommunityID). + Updates(map[string]interface{}{ + "move_out_date": personMoveInout.MoveOutDate, + }).Error + if err != nil { + return err + } + } + } else { + // 濡傛灉璁板綍涓嶅瓨鍦紝鍒欐彃鍏ユ柊璁板綍 + //fmt.Println("鎻掑叆璁板綍澶辫触") + //fmt.Println("data", &personMoveInout) + err := db.Create(&personMoveInout).Error + if err != nil { + return err + } + } + + } + + return nil +} diff --git a/db/person.go b/db/person.go new file mode 100644 index 0000000..0eecb29 --- /dev/null +++ b/db/person.go @@ -0,0 +1,46 @@ +package db + +import "strconv" + +// 鏍规嵁dbtablepersons琛╥d鏌ヨ鐩爣妗f骞撮緞 +func QueryAgeById(id string) (int, error) { + var db = DB + var age string + err := db.Table("person"). + Select("age"). + Where("id = ?", id). + Scan(&age).Error + if err != nil { + return 0, err + } + + return strconv.Atoi(age) +} + +// 鏌ヨ浜虹墿骞撮緞 +func GetAgeById(id string) (int, error) { + var db = DB + // 鏌ヨ鏁版嵁 + var age string + if err := db.Table("person"). + Select("age"). + Where("id = ?", id). + Find(&age).Error; err != nil { + return 0, err + } + + return strconv.Atoi(age) +} + +// 鏌ヨ浜虹墿韬唤璇佸彿 +func GetIdCardById(id string) string { + var db = DB + // 鏌ヨ鏁版嵁 + var idCard string + db.Table("person"). + Select("id_card"). + Where("id = ?", id). + Find(&idCard) + + return idCard +} diff --git a/db/personLabel.go b/db/personLabel.go new file mode 100644 index 0000000..8846037 --- /dev/null +++ b/db/personLabel.go @@ -0,0 +1,73 @@ +package db + +import ( + "basic.com/valib/logger.git" + "errors" + "gorm.io/gorm" + "time" +) + +type Identity struct { + ID string `gorm:"primary_key;column:id;type:varchar(255);" json:"id"` + CreatedAt time.Time + UpdatedAt time.Time + DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` + CommunityID string `gorm:"column:community_id"` + DocumentNumber string `gorm:"column:person_id"` + LabelId string `gorm:"column:label_id"` + ExpireTime int64 `gorm:"column:expire_time"` +} + +func (Identity) TableName() string { + return "person_label" +} + +// UpdatePersonInfo 鏇存柊鎴栨彃鍏ュ涓汉鍛樿韩浠戒俊鎭� +func UpdateDBPersonLabel(personsIdentity []Identity) error { + var db = DB + // 閬嶅巻浜哄憳淇℃伅 + for _, personIdentity := range personsIdentity { + + // 妫�鏌ヨ褰曟槸鍚﹀瓨鍦� + var existingPerson Identity + err := db.Where("person_id = ? AND community_id = ? AND label_id = ?", + personIdentity.DocumentNumber, + personIdentity.CommunityID, + personIdentity.LabelId, + ).First(&existingPerson).Error + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { + logger.Error("Query person error:", err, + personIdentity.DocumentNumber, + personIdentity.CommunityID, + personIdentity.LabelId) + //fmt.Println("asdasfasfasf") + continue + //return err + } + + // 濡傛灉璁板綍瀛樺湪锛屽垯鏇存柊 + if existingPerson.DocumentNumber != "" { + err := db.Model(&Identity{}). + Where("person_id = ? AND community_id = ? AND label_id = ?", + personIdentity.DocumentNumber, + personIdentity.CommunityID, + personIdentity.LabelId, + ). + Updates(map[string]interface{}{ + "expire_time": personIdentity.ExpireTime, + }).Error + if err != nil { + return err + } + } else { + // 濡傛灉璁板綍涓嶅瓨鍦紝鍒欐彃鍏ユ柊璁板綍 + err := db.Create(&personIdentity).Error + if err != nil { + return err + } + } + + } + + return nil +} diff --git a/db/personStatusRule.go b/db/personStatusRule.go new file mode 100644 index 0000000..6d4f5c9 --- /dev/null +++ b/db/personStatusRule.go @@ -0,0 +1,27 @@ +package db + +type PersonnelStatusRule struct { + ID int `gorm:"column:id"` + Name string `gorm:"column:name"` + DetectionCountStart int `gorm:"column:capture_count_start"` + DetectionCountEnd int `gorm:"column:capture_count_end"` + DetectionDaysStart int `gorm:"column:capture_days_start"` + DetectionDaysEnd int `gorm:"column:capture_days_end"` + Status string `gorm:"column:status"` +} + +func (psr *PersonnelStatusRule) TableName() string { + return "person_status_rule" +} + +// 鏌ヨ鍏ㄩ儴鏁版嵁 +func GetAllData() ([]PersonnelStatusRule, error) { + var db = DB + + var rules []PersonnelStatusRule + if err := db.Find(&rules).Error; err != nil { + return nil, err + } + + return rules, nil +} diff --git a/db/publicHouse.go b/db/publicHouse.go new file mode 100644 index 0000000..52a90cc --- /dev/null +++ b/db/publicHouse.go @@ -0,0 +1,27 @@ +package db + +type PublicHouse struct { + ID int `gorm:"primaryKey;autoIncrement" json:"id"` // 涓婚敭ID + CommunityID string `gorm:"column:community_id;type:varchar(255)" json:"community_id"` // 灏忓尯ID + Applicant string `gorm:"column:applicant;type:varchar(255)" json:"applicant"` // 鐢宠浜� + IdCard string `gorm:"column:id_card;type:varchar(50)" json:"id_card"` // 璇佷欢缂栧彿 + PhoneNumber string `gorm:"column:phone_number;type:varchar(20)" json:"phone_number"` // 鑱旂郴鐢佃瘽 + Address string `gorm:"column:address;type:varchar(255)" json:"address"` // 鎴垮眿鍦板潃 + ApplicationTime string `gorm:"column:application_time" json:"application_time"` // 鐢宠鏃堕棿 + EndTime string `gorm:"column:end_time" json:"end_time"` // 缁撴潫鏃堕棿 +} + +func (PublicHouse) TableName() string { + return "public_house" +} + +func GetPublicHouseData() ([]PublicHouse, error) { + // 鏌ヨ鏁版嵁 + var db = DB + var ph []PublicHouse + result := db.Table("public_house").Where("1 = 1").Find(&ph) + if result.Error != nil { + return nil, result.Error + } + return ph, nil +} diff --git a/db/repository.go b/db/repository.go index ca159f7..f948b01 100644 --- a/db/repository.go +++ b/db/repository.go @@ -1,330 +1,14 @@ package db -import ( - "basic.com/valib/logger.git" - "errors" - "gorm.io/gorm" - "strconv" -) - // 鏌ヨ灏忓尯琛� func GetCommunityIDs() ([]string, error) { // 鏌ヨ鏁版嵁 var db = DB var communityIDs []string - result := db.Table("domain_unit").Where("domainType = ?", 1).Pluck("id", &communityIDs) + result := db.Table("domain_unit").Where("domain_type = ?", 1).Pluck("id", &communityIDs) if result.Error != nil { return nil, result.Error } return communityIDs, nil -} - -// 鏌ヨ璁惧琛� -func GetDeviceData() ([]Device, error) { - // 鏌ヨ鏁版嵁 - var db = DB - var device []Device - result := db.Table("device").Where("communityID != ?", "").Find(&device) - if result.Error != nil { - return nil, result.Error - } - return device, nil -} - -func GetPublicHouseData() ([]PublicHouse, error) { - // 鏌ヨ鏁版嵁 - var db = DB - var ph []PublicHouse - result := db.Table("public_house").Where("1 = 1").Find(&ph) - if result.Error != nil { - return nil, result.Error - } - return ph, nil -} - -// 鏌ヨ鍏ㄩ儴鏁版嵁 -func GetAllTaskData() ([]Task, error) { - var db = DB - var task []Task - if err := db.Find(&task).Error; err != nil { - return nil, err - } - - return task, nil -} - -// 鏌ヨ鍏ㄩ儴鏁版嵁 -func GetAllData() ([]PersonnelStatusRule, error) { - var db = DB - var rules []PersonnelStatusRule - if err := db.Find(&rules).Error; err != nil { - return nil, err - } - - return rules, nil -} - -// 鏌ヨ浣忔埛鏃堕棿鏁版嵁 -func GetResidentData(status, communityID string) ([]Resident, error) { - var residents []Resident - //var db = DB.Debug() - var db = DB - // 鎵ц鏌ヨ - rows, err := db.Table("snapshot_count_summary"). - Select("document_number", "community_id", "last_appearance_time", "created_at"). - Where("status = ? AND community_id = ?", status, communityID). - //Where("snapshot_count_summary.created_at is not null"). - Rows() - if err != nil { - return nil, err - } - defer rows.Close() - - // 閬嶅巻鏌ヨ缁撴灉 - for rows.Next() { - var resident Resident - err := rows.Scan(&resident.DocumentNumber, &resident.CommunityId, &resident.LastAppearanceTime, &resident.CreateAt) - if err != nil { - logger.Error("err: ", err) - return nil, err - } - //fmt.Println("resident111: ", resident) - residents = append(residents, resident) - } - if err := rows.Err(); err != nil { - return nil, err - } - - return residents, nil -} - -// 鏌ヨ浜虹墿灞炴�� -func GetDBPersonStatus(id, communityId string) string { - var db = DB - - // 鏌ヨ鏁版嵁 - var personStatus string - db.Table("snapshot_count_summary"). - Select("status"). - Where("community_id = ? and document_number = ?", communityId, id). - Find(&personStatus) - - return personStatus -} - -// 鏌ヨ灏忓尯妗f琛� (鍘熸煡璇换鍔″睘鎬�) -func QueryPersonStatusWithPagination(community_id string, timeThreshold int64) ([]*PersonStatus, error) { - var db = DB - var personStatusList []*PersonStatus - result := db.Select("document_number, status, frequent_address, last_appearance_time, last_appearance_status_time"). - Where("community_id = ? AND last_appearance_time != last_appearance_status_time AND last_appearance_time > ?", community_id, timeThreshold). - Find(&personStatusList) - if result.Error != nil { - logger.Error(result.Error) - return nil, result.Error - } - return personStatusList, nil -} - -// 鏌ヨ浜虹墿骞撮緞 -func GetAgeById(id string) (int, error) { - var db = DB - // 鏌ヨ鏁版嵁 - var age string - if err := db.Table("dbtablepersons"). - Select("age"). - Where("id = ?", id). - Find(&age).Error; err != nil { - return 0, err - } - - return strconv.Atoi(age) -} - -// 鏌ヨ浜虹墿韬唤璇佸彿 -func GetIdCardById(id string) string { - var db = DB - // 鏌ヨ鏁版嵁 - var idCard string - db.Table("dbtablepersons"). - Select("idCard"). - Where("id = ?", id). - Find(&idCard) - - return idCard -} - -//// 鏍规嵁绀惧尯id鍜屼綇鎴峰睘鎬ф煡璇綇鎴锋。妗堢紪鍙� -//func GetDocNumberFromPersonStatus(id, status string) ([]string, error) { -// var db = DB -// // 鏌ヨ鏁版嵁 -// var personStatusList []PersonStatus -// if err := db.Table("person_status"). -// Select("documentNumber, status, frequentAddress"). -// Where("communityID = ? AND status = ?", id, status). -// Find(&personStatusList).Error; err != nil { -// return nil, err -// } -// -// docNum := make([]string, 0) -// for _, ps := range personStatusList { -// docNum = append(docNum, ps.DocumentNumber) -// } -// -// return docNum, nil -//} - -// 鏌ヨ浜虹墿韬唤灞炴�ц〃 -func GetLabelManageIdentity(IdentityType int) ([]LabelManage, error) { - var db = DB - // 鏌ヨ鏁版嵁 - var labelManageIdentity []LabelManage - if err := db.Table("label_manage"). - Select("id, name, valid_days"). - Where("type = ?", IdentityType). - Find(&labelManageIdentity).Error; err != nil { - return nil, err - } - - return labelManageIdentity, nil -} - -// 鏍规嵁dbtablepersons琛╥d鏌ヨ鐩爣妗f骞撮緞 -func QueryAgeById(id string) (int, error) { - var db = DB - var age string - err := db.Table("dbtablepersons"). - Select("age"). - Where("id = ?", id). - Scan(&age).Error - if err != nil { - return 0, err - } - - return strconv.Atoi(age) -} - -// UpdatePersonInfo 鏇存柊鎴栨彃鍏ュ涓汉鍛樹俊鎭� -func UpdateMoveInout(personsMoveInout []MoveInout) error { - var db = DB - // 閬嶅巻浜哄憳淇℃伅 - for _, personMoveInout := range personsMoveInout { - - // 妫�鏌ヨ褰曟槸鍚﹀瓨鍦� - var existingPerson MoveInout - err := db.Where("document_number = ? AND community_id = ?", personMoveInout.DocumentNumber, personMoveInout.CommunityID).First(&existingPerson).Error - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - logger.Error("Query person error:", err, personMoveInout.DocumentNumber, personMoveInout.CommunityID) - //fmt.Println("asdasfasfasf") - continue - //return err - } - - // 濡傛灉璁板綍瀛樺湪锛屽垯鏇存柊 - if existingPerson.DocumentNumber != "" { - //fmt.Println("existingPerson.DocumentNumber: ", existingPerson.DocumentNumber) - if existingPerson.Status != "Verified" { - err := db.Model(&MoveInout{}). - Where("document_number = ? AND community_id = ?", personMoveInout.DocumentNumber, personMoveInout.CommunityID). - Updates(map[string]interface{}{ - "status": personMoveInout.Status, - "move_out_date": personMoveInout.MoveOutDate, - }).Error - if err != nil { - return err - } - } else { - err := db.Model(&MoveInout{}). - Where("document_number = ? AND community_id = ?", personMoveInout.DocumentNumber, personMoveInout.CommunityID). - Updates(map[string]interface{}{ - "move_out_date": personMoveInout.MoveOutDate, - }).Error - if err != nil { - return err - } - } - } else { - // 濡傛灉璁板綍涓嶅瓨鍦紝鍒欐彃鍏ユ柊璁板綍 - //fmt.Println("鎻掑叆璁板綍澶辫触") - //fmt.Println("data", &personMoveInout) - err := db.Create(&personMoveInout).Error - if err != nil { - return err - } - } - - } - - return nil -} - -// UpdatePersonInfo 鏇存柊鎴栨彃鍏ュ涓汉鍛樿韩浠戒俊鎭� -func UpdateDBPersonLabel(personsIdentity []Identity) error { - var db = DB - // 閬嶅巻浜哄憳淇℃伅 - for _, personIdentity := range personsIdentity { - - // 妫�鏌ヨ褰曟槸鍚﹀瓨鍦� - var existingPerson Identity - err := db.Where("dbtablepersons_id = ? AND community_id = ? AND label_id = ?", - personIdentity.DocumentNumber, - personIdentity.CommunityID, - personIdentity.LabelId, - ).First(&existingPerson).Error - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - logger.Error("Query person error:", err, - personIdentity.DocumentNumber, - personIdentity.CommunityID, - personIdentity.LabelId) - //fmt.Println("asdasfasfasf") - continue - //return err - } - - // 濡傛灉璁板綍瀛樺湪锛屽垯鏇存柊 - if existingPerson.DocumentNumber != "" { - err := db.Model(&Identity{}). - Where("dbtablepersons_id = ? AND community_id = ? AND label_id = ?", - personIdentity.DocumentNumber, - personIdentity.CommunityID, - personIdentity.LabelId, - ). - Updates(map[string]interface{}{ - "expire_time": personIdentity.ExpireTime, - }).Error - if err != nil { - return err - } - } else { - // 濡傛灉璁板綍涓嶅瓨鍦紝鍒欐彃鍏ユ柊璁板綍 - err := db.Create(&personIdentity).Error - if err != nil { - return err - } - } - - } - - return nil -} - -// UpdatePersonInfo 鏇存柊鎴栨彃鍏ュ涓汉鍛樹俊鎭� -func UpdatePersonInfo(persons []PersonStatus, communityID string) error { - var db = DB - // 閬嶅巻浜哄憳淇℃伅 - for _, person := range persons { - err := db.Model(&PersonStatus{}). - Where("document_number = ? AND community_id = ?", person.DocumentNumber, communityID). - Updates(map[string]interface{}{ - "status": person.Status, - "frequent_address": person.FrequentAddress, - "LastAppearanceStatusTime": person.LastAppearanceStatusTime, - }).Error - if err != nil { - return err - } - } - - return nil } diff --git a/db/summary.go b/db/summary.go new file mode 100644 index 0000000..f1a856c --- /dev/null +++ b/db/summary.go @@ -0,0 +1,117 @@ +package db + +import ( + "basic.com/valib/logger.git" + "gorm.io/gorm" + "time" +) + +type PersonStatus struct { + ID string `gorm:"primary_key;column:id;type:varchar(255);" json:"id"` + CreatedAt time.Time + UpdatedAt time.Time + DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` + OrgId string `gorm:"column:org_id"` // 娲惧嚭鎵�id + CommunityID string `gorm:"column:community_id"` // 灏忓尯id + DocumentNumber string `gorm:"column:document_number"` // 妗f缂栧彿 + DaysAppeared int `gorm:"column:days_appeared"` // 鍑虹幇澶╂暟 + Count int `gorm:"column:count"` // 鎶撴媿娆℃暟 + Status string `gorm:"column:status"` // 鏍囩 + LastAppearanceTime int64 `gorm:"column:last_appearance_time"` // 鏈�鍚庡嚭鐜版椂闂� + LastAppearanceStatusTime int64 `gorm:"column:last_appearance_status_time"` // 鏈�鍚庡嚭鐜版椂闂� + LastLocation string `gorm:"column:last_location"` // 鏈�鍚庡嚭鐜板湴鐐� + FrequentAddress string `gorm:"column:frequent_address"` // 甯镐綇鍦板潃 +} + +func (PersonStatus) TableName() string { + return "snapshot_count_summary" +} + +type Resident struct { + CommunityId string `gorm:"column:community_id"` + DocumentNumber string `gorm:"column:document_number"` + LastAppearanceTime int64 `gorm:"column:last_appearance_time"` + CreateAt string `gorm:"column:create_at"` +} + +// 鏌ヨ浣忔埛鏃堕棿鏁版嵁 +func GetResidentData(status, communityID string) ([]Resident, error) { + var residents []Resident + //var db = DB.Debug() + var db = DB + // 鎵ц鏌ヨ + rows, err := db.Table("snapshot_count_summary"). + Select("document_number", "community_id", "last_appearance_time", "created_at"). + Where("status = ? AND community_id = ?", status, communityID). + //Where("snapshot_count_summary.created_at is not null"). + Rows() + if err != nil { + return nil, err + } + defer rows.Close() + + // 閬嶅巻鏌ヨ缁撴灉 + for rows.Next() { + var resident Resident + err := rows.Scan(&resident.DocumentNumber, &resident.CommunityId, &resident.LastAppearanceTime, &resident.CreateAt) + if err != nil { + logger.Error("err: ", err) + return nil, err + } + //fmt.Println("resident111: ", resident) + residents = append(residents, resident) + } + if err := rows.Err(); err != nil { + return nil, err + } + + return residents, nil +} + +// 鏌ヨ浜虹墿灞炴�� +func GetDBPersonStatus(id, communityId string) string { + var db = DB + + // 鏌ヨ鏁版嵁 + var personStatus string + db.Table("snapshot_count_summary"). + Select("status"). + Where("community_id = ? and document_number = ?", communityId, id). + Find(&personStatus) + + return personStatus +} + +// 鏌ヨ灏忓尯妗f琛� (鍘熸煡璇换鍔″睘鎬�) +func QueryPersonStatusWithPagination(community_id string, timeThreshold int64) ([]*PersonStatus, error) { + var db = DB + var personStatusList []*PersonStatus + result := db.Select("document_number, status, frequent_address, last_appearance_time, last_appearance_status_time"). + Where("community_id = ? AND last_appearance_time != last_appearance_status_time AND last_appearance_time > ?", community_id, timeThreshold). + Find(&personStatusList) + if result.Error != nil { + logger.Error(result.Error) + return nil, result.Error + } + return personStatusList, nil +} + +// UpdatePersonInfo 鏇存柊鎴栨彃鍏ュ涓汉鍛樹俊鎭� +func UpdatePersonInfo(persons []PersonStatus, communityID string) error { + var db = DB + // 閬嶅巻浜哄憳淇℃伅 + for _, person := range persons { + err := db.Model(&PersonStatus{}). + Where("document_number = ? AND community_id = ?", person.DocumentNumber, communityID). + Updates(map[string]interface{}{ + "status": person.Status, + "frequent_address": person.FrequentAddress, + "LastAppearanceStatusTime": person.LastAppearanceStatusTime, + }).Error + if err != nil { + return err + } + } + + return nil +} diff --git a/db/task.go b/db/task.go new file mode 100644 index 0000000..a64ab90 --- /dev/null +++ b/db/task.go @@ -0,0 +1,30 @@ +package db + +import ( + "gorm.io/gorm" + "time" +) + +type Task struct { + Id int `gorm:"column:id"` + Name string `gorm:"column:name"` + disabled bool `gorm:"column:disabled,default:0"` + CreatedAt time.Time + UpdatedAt time.Time + DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` +} + +func (Task) TableName() string { + return "surveillance_task" +} + +// 鏌ヨ鍏ㄩ儴鏁版嵁 +func GetAllTaskData() ([]Task, error) { + var db = DB + var task []Task + if err := db.Find(&task).Error; err != nil { + return nil, err + } + + return task, nil +} diff --git a/rule/engine.go b/rule/engine.go index 8d3322f..95fdafd 100644 --- a/rule/engine.go +++ b/rule/engine.go @@ -17,19 +17,17 @@ // 閬嶅巻Resident缁撴瀯浣撳垏鐗� for _, resident := range residents { - //fmt.Println("gogogogo!!!!!!!!!!!!!!!!!!!!!!!!!!!") // 灏嗗瓧绗︿覆绫诲瀷鐨勬椂闂磋浆鎹负time.Time绫诲瀷锛屽苟鍙繚鐣欏勾鏈堟棩 lastAppearanceTime := time.Unix(resident.LastAppearanceTime, 0) lastAppearanceDate := time.Date(lastAppearanceTime.Year(), lastAppearanceTime.Month(), lastAppearanceTime.Day(), 0, 0, 0, 0, lastAppearanceTime.Location()) - //lastAppearanceTime, err := time.Parse("2006-01-02", resident.LastAppearanceTime) - datePart := strings.Split(resident.CreateAt, "T")[0] - createdAt, err := time.Parse("2006-01-02", datePart) + createdAt, err := time.Parse("2006-01-02", resident.CreateAt) if err != nil { fmt.Println(err) // 澶勭悊鏃堕棿瑙f瀽閿欒 // 鍙互閫夋嫨璺宠繃璇ユ潯鏁版嵁鎴栬�呰褰曟棩蹇� continue } + // 璁$畻LastAppearanceTime鍜孋reateAt璺濈褰撳墠鏃ユ湡鐨勫ぉ鏁� daysSinceLastAppearance := currentDate.Sub(lastAppearanceDate).Hours() / 24 daysSinceCreateAt := currentDate.Sub(createdAt).Hours() / 24 @@ -63,8 +61,8 @@ moveInout = append(moveInout, db.MoveInout{ DocumentNumber: resident.DocumentNumber, CommunityID: resident.CommunityId, - MoveInDate: createdAt, // 瀛樺偍骞存湀鏃� - MoveOutDate: &lastAppearanceDate, // 瀛樺偍骞存湀鏃� + MoveInDate: createdAt.Format("2006-01-02"), // 瀛樺偍骞存湀鏃� + MoveOutDate: lastAppearanceDate.Format("2006-01-02"), // 瀛樺偍骞存湀鏃� MoveType: moveType, Status: status, }) @@ -84,7 +82,7 @@ // return true, nil //} -func CreateLinearModel(personInfos []db.CaptureInfo, communityID string, threshold float64, validDays int, labelId int) ([]db.Identity, []db.CaptureInfo) { +func CreateLinearModel(personInfos []db.CaptureInfo, communityID string, threshold float64, validDays int, labelId string) ([]db.Identity, []db.CaptureInfo) { identity := make([]db.Identity, 0) captureInfo := make([]db.CaptureInfo, 0) for _, info := range personInfos { @@ -203,21 +201,21 @@ identity = append(identity, db.Identity{ CommunityID: communityID, DocumentNumber: info.DocumentNumber, - LabelId: labelManage[lIndex].Id, + LabelId: labelManage[lIndex].ID, ExpireTime: GetCurrentDateAddDaysTimestamp(labelManage[lIndex].ValidDays)}) } else if info.Age >= 23 && info.Age <= 60 { lIndex := labelIndexMap["涓婄彮鏃�"] identity = append(identity, db.Identity{ CommunityID: communityID, DocumentNumber: info.DocumentNumber, - LabelId: labelManage[lIndex].Id, + LabelId: labelManage[lIndex].ID, ExpireTime: GetCurrentDateAddDaysTimestamp(labelManage[lIndex].ValidDays)}) } else if info.Age > 60 { lIndex := labelIndexMap["绂婚��浼戜汉鍛�"] identity = append(identity, db.Identity{ CommunityID: communityID, DocumentNumber: info.DocumentNumber, - LabelId: labelManage[lIndex].Id, + LabelId: labelManage[lIndex].ID, ExpireTime: GetCurrentDateAddDaysTimestamp(labelManage[lIndex].ValidDays)}) } //fmt.Println("涓婄彮鏃�", info.DocumentNumber, info.Age, countMaxRows, colS, colE) @@ -230,21 +228,21 @@ identity = append(identity, db.Identity{ CommunityID: communityID, DocumentNumber: info.DocumentNumber, - LabelId: labelManage[lIndex].Id, + LabelId: labelManage[lIndex].ID, ExpireTime: GetCurrentDateAddDaysTimestamp(labelManage[lIndex].ValidDays)}) } else if info.Age >= 23 && info.Age <= 60 { lIndex := labelIndexMap["涓婄彮鏃�"] identity = append(identity, db.Identity{ CommunityID: communityID, DocumentNumber: info.DocumentNumber, - LabelId: labelManage[lIndex].Id, + LabelId: labelManage[lIndex].ID, ExpireTime: GetCurrentDateAddDaysTimestamp(labelManage[lIndex].ValidDays)}) } else if info.Age > 60 { lIndex := labelIndexMap["绂婚��浼戜汉鍛�"] identity = append(identity, db.Identity{ CommunityID: communityID, DocumentNumber: info.DocumentNumber, - LabelId: labelManage[lIndex].Id, + LabelId: labelManage[lIndex].ID, ExpireTime: GetCurrentDateAddDaysTimestamp(labelManage[lIndex].ValidDays)}) } //fmt.Println("涓婄彮鏃�", info.DocumentNumber, info.Age, countMaxRows, colS, colE) diff --git a/rule/service.go b/rule/service.go index b670028..dfcb083 100644 --- a/rule/service.go +++ b/rule/service.go @@ -87,7 +87,7 @@ cameraIds := make([]string, 0) for _, deviceInfo := range cache.Device { - if deviceInfo.AreaID == communityId && deviceInfo.BuildingType == db.BuildingTypeMixedUse { + if deviceInfo.CommunityID == communityId && deviceInfo.BuildingType == db.BuildingTypeMixedUse { cameraIds = append(cameraIds, deviceInfo.DeviceCode) } } @@ -137,7 +137,7 @@ if err != nil { logger.Error("GetCommunityIDs Error", err) } - labeManage, err := db.GetLabelManageIdentity(2) + labeManage, err := db.GeIdentityLabels() if err != nil { logger.Error("GetDBPersonStatusData Error", err) } @@ -223,7 +223,7 @@ for _, identity := range labeManage { switch identity.Name { case "鏈嶅姟浜哄憳": - identity, attribute := CreateLinearModel(captureInfos, communityID, 2.68, identity.ValidDays, identity.Id) + identity, attribute := CreateLinearModel(captureInfos, communityID, 2.68, identity.ValidDays, identity.ID) errIdentity := db.UpdateDBPersonLabel(identity) if errIdentity != nil { -- Gitblit v1.8.0