Files
simrsx-be/internal/use-case/simgos-sync-use-case/seeder/helper.go
T
2025-12-11 18:35:43 +07:00

112 lines
2.5 KiB
Go

package seeder
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
es "simrs-vx/internal/domain/main-entities/user"
cfg "simrs-vx/internal/infra/sync-cfg"
"time"
)
type Dto struct {
LoginNip []string `json:"loginNip"`
Instalasi_Code string `json:"instalasi_code"`
SeedTableName string `json:"seedTableName"`
}
func Send(method string, endpoint string, body *bytes.Buffer, username string) ([]byte, error) {
var url string = cfg.O.NewHost + "v1/" + endpoint
var reader io.Reader = nil
if body != nil {
reader = body
}
req, err := http.NewRequest(method, url, reader)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Sync-Source", cfg.O.OldSource)
req.Header.Set("X-Sync-SecretKey", cfg.O.NewSecretKey)
req.Header.Set("X-Sync-UserName", username)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http status code %d", resp.StatusCode)
}
respBody, _ := io.ReadAll(resp.Body)
return respBody, nil
}
func CreateUser(user es.CreateDto) (*es.User, error) {
var path = "user"
// create request body
jsonUser, err := json.Marshal(user)
if err != nil {
return nil, err
}
reqBody := bytes.NewBuffer(jsonUser)
// send data to main-api
resp, err := Send(http.MethodPost, path, reqBody, "von")
if err != nil {
return nil, err
}
type MetaData struct {
Source string `json:"source"`
Status string `json:"status"`
Structure string `json:"structure"`
}
type MainApiResp struct {
Meta MetaData `json:"meta"`
Data es.User `json:"data"`
}
// getting response
var data MainApiResp
err = json.Unmarshal(resp, &data)
if err != nil {
return nil, err
}
return &data.Data, nil
}
func GenerateDummyNIK(gender string) string {
rand.Seed(time.Now().UnixNano())
// 1️⃣ Kode wilayah (6 digit)
// Bisa di-random, atau gunakan kode tetap seperti Jakarta: 317301
region := rand.Intn(999999) // 000000 - 999999
regionCode := fmt.Sprintf("%06d", region)
// 2️⃣ Tanggal lahir (DDMMYY)
year := rand.Intn(30) + 70 // antara tahun 1970-1999 (bisa diganti range lain)
month := rand.Intn(12) + 1
day := rand.Intn(28) + 1 // selalu valid
if gender == "F" {
day += 40 // aturan NIK perempuan: tanggal lahir + 40
}
birth := fmt.Sprintf("%02d%02d%02d", day, month, year)
// 3️⃣ Nomor urut (4 digit)
sequence := fmt.Sprintf("%04d", rand.Intn(9999))
// 4️⃣ Susun NIK akhir
nik := regionCode + birth + sequence
return nik
}