update ignore
This commit is contained in:
No files matched your search
@@ -0,0 +1,26 @@
|
||||
package condition
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// ConditionDB merepresentasikan struktur tabel diagnosa medis
|
||||
// TODO: Sesuaikan field dan tag `db` dengan tabel SIMRS Anda yang sebenarnya
|
||||
type ConditionDB struct {
|
||||
IdxDiagnosa int64 `db:"idxdiagnosa"` // Primary Key
|
||||
IdxDaftar int64 `db:"idxdaftar"` // Relasi ke Encounter
|
||||
NoMR sql.NullString `db:"nomr"`
|
||||
TglDiagnosa sql.NullTime `db:"tgl_diagnosa"`
|
||||
KdICD10 sql.NullString `db:"kd_icd10"` // Kode Penyakit ICD-10
|
||||
NamaPenyakit sql.NullString `db:"nama_penyakit"`
|
||||
}
|
||||
|
||||
// ConditionSyncLog merepresentasikan struktur log sinkronisasi API SatuSehat.
|
||||
type ConditionSyncLog struct {
|
||||
IdxDiagnosa int64 `db:"idxdiagnosa"`
|
||||
ConditionID string `db:"condition_id"` // ID dari SatuSehat jika SUCCESS
|
||||
RequestPayload string `db:"request_payload"` // Teks JSON raw request
|
||||
ResponsePayload string `db:"response_payload"` // Teks JSON raw response
|
||||
Status string `db:"status"` // Status: SUCCESS / FAILED
|
||||
ErrorMessage string `db:"error_message"` // Pesan kegagalan
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package condition
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"service/pkg/logger"
|
||||
)
|
||||
|
||||
// MapToInternalAPI memetakan data database menjadi payload untuk Internal API
|
||||
// TODO: Sesuaikan dengan JSON Payload endpoint Condition Anda
|
||||
func MapToInternalAPI(dbData *ConditionDB, orgID string) map[string]interface{} {
|
||||
waktuDiagnosa := logger.LocalNow()
|
||||
if dbData.TglDiagnosa.Valid {
|
||||
waktuDiagnosa = dbData.TglDiagnosa.Time
|
||||
}
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"condition_id": fmt.Sprintf("%d", dbData.IdxDiagnosa),
|
||||
"encounter_id": fmt.Sprintf("%d", dbData.IdxDaftar),
|
||||
"patient_id": dbData.NoMR.String, // Perlu diganti IHS Number di service
|
||||
"code": dbData.KdICD10.String,
|
||||
"display": dbData.NamaPenyakit.String,
|
||||
"recorded_date": waktuDiagnosa.Format(time.RFC3339),
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func MapToSyncLog(idx int64, fhirID string, reqPayload interface{}, respBody []byte, status string, errMsg string) ConditionSyncLog {
|
||||
reqBytes, _ := json.MarshalIndent(reqPayload, "", " ")
|
||||
return ConditionSyncLog{
|
||||
IdxDiagnosa: idx,
|
||||
ConditionID: fhirID,
|
||||
RequestPayload: string(reqBytes),
|
||||
ResponsePayload: string(respBody),
|
||||
Status: status,
|
||||
ErrorMessage: errMsg,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package condition
|
||||
|
||||
import (
|
||||
"context"
|
||||
"service/internal/infrastructure/database"
|
||||
"service/pkg/utils/query"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetNextCondition(ctx context.Context, lastID int64) (*ConditionDB, error)
|
||||
SaveSatuSehatID(ctx context.Context, idx int64, fhirID string) error
|
||||
SaveSyncLog(ctx context.Context, logData ConditionSyncLog) error
|
||||
}
|
||||
|
||||
type repository struct {
|
||||
dbManager database.Service
|
||||
}
|
||||
|
||||
func NewRepository(dbManager database.Service) Repository {
|
||||
return &repository{dbManager: dbManager}
|
||||
}
|
||||
|
||||
func (r *repository) GetNextCondition(ctx context.Context, lastID int64) (*ConditionDB, error) {
|
||||
var cond ConditionDB
|
||||
simrsDB, err := r.dbManager.GetSQLXDB("simrs")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
qb := query.NewSQLQueryBuilder(query.DBTypePostgreSQL).SetSecurityOptions(false, 0).SetQueryLogging(false)
|
||||
|
||||
// TODO: Sesuaikan dengan nama tabel diagnosa di SIMRS Anda
|
||||
qSimrs := query.DynamicQuery{
|
||||
From: "public.t_diagnosa",
|
||||
Filters: []query.FilterGroup{
|
||||
{
|
||||
Filters: []query.DynamicFilter{
|
||||
query.CreateFilter("idxdiagnosa", query.OpGreaterThan, lastID),
|
||||
},
|
||||
},
|
||||
},
|
||||
Sort: []query.SortField{
|
||||
query.CreateAscSort("idxdiagnosa"),
|
||||
},
|
||||
Limit: 1,
|
||||
}
|
||||
|
||||
err = qb.ExecuteQueryRow(ctx, simrsDB, qSimrs, &cond)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cond, nil
|
||||
}
|
||||
|
||||
func (r *repository) SaveSatuSehatID(ctx context.Context, idx int64, fhirID string) error {
|
||||
simrsDB, err := r.dbManager.GetSQLXDB("simrs")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
qb := query.NewSQLQueryBuilder(query.DBTypePostgreSQL).SetSecurityOptions(false, 0).SetQueryLogging(false)
|
||||
updateData := query.UpdateData{
|
||||
Columns: []string{"status_bridging"},
|
||||
Values: []interface{}{fhirID},
|
||||
}
|
||||
filters := []query.FilterGroup{
|
||||
query.CreateAndFilterGroup([]query.DynamicFilter{query.CreateEqualFilter("idxdiagnosa", idx)}),
|
||||
}
|
||||
|
||||
_, err = qb.ExecuteUpdate(ctx, simrsDB, "public.t_diagnosa", updateData, filters)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *repository) SaveSyncLog(ctx context.Context, logData ConditionSyncLog) error {
|
||||
simrsDB, err := r.dbManager.GetSQLXDB("simrs")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
qb := query.NewSQLQueryBuilder(query.DBTypePostgreSQL).SetSecurityOptions(false, 0).SetQueryLogging(false)
|
||||
insertData := query.InsertData{
|
||||
Columns: []string{"idxdiagnosa", "condition_id", "request_payload", "response_payload", "status", "error_message"},
|
||||
Values: []interface{}{
|
||||
logData.IdxDiagnosa, logData.ConditionID, logData.RequestPayload,
|
||||
logData.ResponsePayload, logData.Status, logData.ErrorMessage,
|
||||
},
|
||||
}
|
||||
conflictCols := []string{"idxdiagnosa"}
|
||||
updateCols := []string{"condition_id", "request_payload", "response_payload", "status", "error_message"}
|
||||
_, err = qb.ExecuteUpsert(ctx, simrsDB, "public.log_satusehat_condition", insertData, conflictCols, updateCols)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package condition
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"service/internal/infrastructure/database"
|
||||
extapi "service/internal/worker/interface"
|
||||
)
|
||||
|
||||
const trackerFile = "last_migrated_condition_id.txt"
|
||||
|
||||
type Config struct {
|
||||
DBManager database.Service
|
||||
InternalBaseURL string
|
||||
InternalToken string
|
||||
OrganizationID string
|
||||
}
|
||||
|
||||
type WorkerService interface {
|
||||
Run(ctx context.Context)
|
||||
}
|
||||
|
||||
type worker struct {
|
||||
cfg Config
|
||||
repo Repository
|
||||
apiClient extapi.Client
|
||||
}
|
||||
|
||||
func NewWorker(cfg Config) WorkerService {
|
||||
return &worker{
|
||||
cfg: cfg,
|
||||
repo: NewRepository(cfg.DBManager),
|
||||
apiClient: extapi.NewClient(15 * time.Second),
|
||||
}
|
||||
}
|
||||
|
||||
func (w *worker) Run(ctx context.Context) {
|
||||
log.Println("[CONDITION WORKER] Memulai proses sinkronisasi ke API Satu Sehat...")
|
||||
lastID := w.readLastID()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("[CONDITION WORKER] Proses dihentikan oleh sistem.")
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
cond, err := w.repo.GetNextCondition(ctx, lastID)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
log.Printf("[CONDITION WORKER] Gagal mengambil data database: %v\n", err)
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("[CONDITION WORKER] Memproses Diagnosa ID: %d\n", cond.IdxDiagnosa)
|
||||
internalPayload := MapToInternalAPI(cond, w.cfg.OrganizationID)
|
||||
reqURL := fmt.Sprintf("%s/satusehat/condition", strings.TrimRight(w.cfg.InternalBaseURL, "/"))
|
||||
|
||||
respBody, statusCode, err := w.apiClient.PostJSON(ctx, reqURL, w.cfg.InternalToken, internalPayload)
|
||||
|
||||
var status, errMsg, fhirID string
|
||||
if err != nil {
|
||||
status, errMsg = "FAILED", err.Error()
|
||||
log.Printf("[CONDITION WORKER] Gagal HTTP Request (ID %d): %v\n", cond.IdxDiagnosa, err)
|
||||
} else if statusCode != http.StatusOK && statusCode != http.StatusCreated {
|
||||
status, errMsg = "FAILED", fmt.Sprintf("HTTP %d", statusCode)
|
||||
log.Printf("[CONDITION WORKER] Gagal Response ID %d. HTTP: %d, Body: %s\n", cond.IdxDiagnosa, statusCode, string(respBody))
|
||||
} else {
|
||||
status = "SUCCESS"
|
||||
var result map[string]interface{}
|
||||
if errUnmarshal := json.Unmarshal(respBody, &result); errUnmarshal == nil {
|
||||
if data, ok := result["data"].(map[string]interface{}); ok {
|
||||
if id, ok := data["id"].(string); ok {
|
||||
fhirID = id
|
||||
}
|
||||
} else if id, ok := result["id"].(string); ok {
|
||||
fhirID = id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
syncLog := MapToSyncLog(cond.IdxDiagnosa, fhirID, internalPayload, respBody, status, errMsg)
|
||||
_ = w.repo.SaveSyncLog(ctx, syncLog)
|
||||
|
||||
if status == "SUCCESS" && fhirID != "" {
|
||||
_ = w.repo.SaveSatuSehatID(ctx, cond.IdxDiagnosa, fhirID)
|
||||
}
|
||||
|
||||
w.updateTracker(&lastID, cond.IdxDiagnosa)
|
||||
time.Sleep(500 * time.Millisecond) // Rate limiting
|
||||
}
|
||||
}
|
||||
|
||||
func (w *worker) updateTracker(lastID *int64, currentID int64) {
|
||||
*lastID = currentID
|
||||
os.WriteFile(trackerFile, []byte(strconv.FormatInt(*lastID, 10)), 0644)
|
||||
}
|
||||
|
||||
func (w *worker) readLastID() int64 {
|
||||
data, _ := os.ReadFile(trackerFile)
|
||||
id, _ := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
|
||||
return id
|
||||
}
|
||||
Reference in New Issue
Block a user