rename to mocksnow

This commit is contained in:
2025-03-22 17:05:42 +11:00
parent c8c475911b
commit 112ad8da1a
33 changed files with 192 additions and 1802 deletions

View File

@@ -4,9 +4,9 @@ import (
"context"
"log/slog"
"net/http"
"wnzl-snow/db"
"wnzl-snow/internal/secrets"
"wnzl-snow/internal/settings"
"mocksnow/db"
"mocksnow/internal/secrets"
"mocksnow/internal/settings"
"github.com/a-h/templ"
)

View File

@@ -6,7 +6,7 @@ import (
"net/http"
"runtime"
"time"
"wnzl-snow/components/views"
"mocksnow/components/views"
)
// Home handles the home page.

View File

@@ -5,80 +5,16 @@ import (
"encoding/json"
"fmt"
"net/http"
"wnzl-snow/components/views"
"mocksnow/components/views"
"mocksnow/db/queries"
"mocksnow/internal/utils"
)
func (h *Handler) RenderIncomingTable(w http.ResponseWriter, r *http.Request) {
/*
db, err := sql.Open("sqlite3", "./your.db")
if err != nil {
http.Error(w, "Failed to connect to the database", http.StatusInternalServerError)
return
}
defer db.Close()
query := `
SELECT
id,
incident_number,
description,
short_description,
urgency,
impact,
state,
external_id,
work_notes,
assignment_group,
assigned_to,
category,
subcategory,
created_at
FROM incoming
ORDER BY created_at DESC
`
rows, err := db.Query(query)
if err != nil {
http.Error(w, "Failed to query the database", http.StatusInternalServerError)
return
}
defer rows.Close()
var results []views.IncomingRow
for rows.Next() {
var row views.IncomingRow
err := rows.Scan(
&row.ID,
&row.IncidentNumber,
&row.Description,
&row.ShortDescription,
&row.Urgency,
&row.Impact,
&row.State,
&row.ExternalID,
&row.WorkNotes,
&row.AssignmentGroup,
&row.AssignedTo,
&row.Category,
&row.Subcategory,
&row.CreatedAt,
)
if err != nil {
log.Printf("Scan error: %v", err)
continue
}
results = append(results, row)
}
if err := rows.Err(); err != nil {
log.Printf("Row iteration error: %v", err)
}
*/
ctx := context.Background()
h.Logger.Debug("Querying updates table")
results, err := h.Database.Queries().GetReportUpdates(ctx)
results, err := h.Database.Queries().ListIncoming(ctx)
if err != nil {
h.Logger.Error("Unable to query incoming table", "error", err)
w.Header().Set("Content-Type", "application/json")
@@ -101,5 +37,16 @@ func (h *Handler) RenderIncomingTable(w http.ResponseWriter, r *http.Request) {
return
}
views.IncomingTable(results).Render(r.Context(), w)
views.IncomingTable(ConvertIncomingList(results)).Render(r.Context(), w)
}
// Converts a slice of Incoming to []IncomingRow
func ConvertIncomingList(list []queries.Incoming) []views.IncomingRow {
rows := make([]views.IncomingRow, 0, len(list))
for _, in := range list {
var row views.IncomingRow
utils.ConvertStruct(in, &row)
rows = append(rows, row)
}
return rows
}

View File

@@ -1,9 +1,11 @@
package handler
import (
"encoding/json"
"fmt"
"io"
"net/http"
"mocksnow/server/models"
)
// NewSnow receives data from the DMSP Snow New() function
@@ -19,4 +21,15 @@ func (h *Handler) NewSnow(w http.ResponseWriter, r *http.Request) {
} else {
h.Logger.Debug("received input data", "length", len(reqBody))
}
// Decode the JSON body
var inc models.Incident
if err := json.Unmarshal(reqBody, &inc); err != nil {
h.Logger.Error("unable to decode json", "error", err)
http.Error(w, "Invalid JSON body", http.StatusBadRequest)
return
} else {
h.Logger.Debug("successfully decoded JSON")
prettyPrint(inc)
}
}

View File

@@ -1,61 +0,0 @@
package handler
import (
"context"
"encoding/json"
"fmt"
"net/http"
"wnzl-snow/internal/report"
)
func (h *Handler) InventoryReportDownload(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
// Generate the XLSX report
reportData, err := report.CreateInventoryReport(h.Logger, h.Database, ctx)
if err != nil {
h.Logger.Error("Failed to create report", "error", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"status": "ERROR",
"message": fmt.Sprintf("Unable to create xlsx report: '%s'", err),
})
return
}
// Set HTTP headers to indicate file download
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
w.Header().Set("Content-Disposition", `attachment; filename="inventory_report.xlsx"`)
w.Header().Set("File-Name", "inventory_report.xlsx")
// Write the XLSX file to the HTTP response
w.Write(reportData)
}
func (h *Handler) UpdateReportDownload(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
// Generate the XLSX report
reportData, err := report.CreateUpdatesReport(h.Logger, h.Database, ctx)
if err != nil {
h.Logger.Error("Failed to create report", "error", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"status": "ERROR",
"message": fmt.Sprintf("Unable to create xlsx report: '%s'", err),
})
return
}
// Set HTTP headers to indicate file download
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
w.Header().Set("Content-Disposition", `attachment; filename="updates_report.xlsx"`)
w.Header().Set("File-Name", "updates_report.xlsx")
// Write the XLSX file to the HTTP response
w.Write(reportData)
}

View File

@@ -1,42 +0,0 @@
package handler
import (
"context"
"fmt"
"net/http"
)
// VmUpdate receives the CloudEvent for a VM modification or move
func (h *Handler) UpdateCleanup(w http.ResponseWriter, r *http.Request) {
/*
// Get the current time
now := time.Now()
// Get the start of the current day (midnight today)
midnightToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
// Convert to Unix time
unixTime := midnightToday.Unix()
// create the database parameters
params := queries.CleanupUpdatesParams{
UpdateType: "diskchange",
UpdateTime: sql.NullInt64{Int64: unixTime, Valid: unixTime > 0},
}
h.Logger.Debug("database params", "params", params)
err := h.Database.Queries().CleanupUpdates(context.Background(), params)
*/
//err := h.Database.Queries().InventoryCleanupTemplates(context.Background())
err := h.Database.Queries().CleanupUpdatesNullVm(context.Background())
if err != nil {
h.Logger.Error("Error received cleaning updates table", "error", err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Delete Request unsuccessful %s\n", err)
} else {
h.Logger.Debug("Processed update cleanup successfully")
w.WriteHeader(http.StatusOK)
// TODO - return some JSON
fmt.Fprintf(w, "Processed update cleanup successfully")
}
}

View File

@@ -2,7 +2,7 @@ package middleware
import (
"net/http"
"wnzl-snow/version"
"mocksnow/version"
)
// CacheMiddleware sets the Cache-Control header based on the version.

View File

@@ -1,9 +1,5 @@
package models
import (
"encoding/json"
)
type IncidentResponse struct {
ImportSet string `json:"import_set"`
StagingTable string `json:"staging_table"`
@@ -37,256 +33,3 @@ type Incident struct {
Category string `json:"category,omitempty"`
SubCategory string `json:"subcategory,omitempty"`
}
type CloudEventReceived struct {
CloudEvent struct {
ID string `json:"id"`
Specversion string `json:"specversion"`
Source string `json:"source"`
Type string `json:"type"`
Time string `json:"time"` // Modified from time.Time
Data struct {
ChainID int `json:"ChainId"`
ChangeTag string `json:"ChangeTag"`
ComputeResource struct {
ComputeResource struct {
Type string `json:"Type"`
Value string `json:"Value"`
} `json:"ComputeResource"`
Name string `json:"Name"`
} `json:"ComputeResource"`
CreatedTime string `json:"CreatedTime"` // Modified from time.Time
Datacenter struct {
Datacenter struct {
Type string `json:"Type"`
Value string `json:"Value"`
} `json:"Datacenter"`
Name string `json:"Name"`
} `json:"Datacenter"`
Ds interface{} `json:"Ds"`
Dvs interface{} `json:"Dvs"`
FullFormattedMessage string `json:"FullFormattedMessage"`
Host struct {
Host struct {
Type string `json:"Type"`
Value string `json:"Value"`
} `json:"Host"`
Name string `json:"Name"`
} `json:"Host"`
Key int `json:"Key"`
Net interface{} `json:"Net"`
NewParent *CloudEventResourcePool `json:"NewParent"`
OldParent *CloudEventResourcePool `json:"OldParent"`
SrcTemplate *CloudEventVm `json:"SrcTemplate"`
Template bool `json:"Template"`
UserName string `json:"UserName"`
VM struct {
Name string `json:"Name"`
VM struct {
Type string `json:"Type"`
Value string `json:"Value"`
} `json:"Vm"`
} `json:"Vm"`
ConfigSpec *json.RawMessage `json:"configSpec"`
ConfigChanges *ConfigChangesReceived `json:"configChanges"` // Modified to separate struct
} `json:"data"`
} `json:"cloudEvent"`
}
type CloudEventResourcePool struct {
Name string `json:"Name"`
ResourcePool struct {
Type string `json:"Type"`
Value string `json:"Value"`
} `json:"ResourcePool"`
}
type CloudEventVm struct {
Name string `json:"Name"`
VM struct {
Type string `json:"Type"`
Value string `json:"Value"`
} `json:"Vm"`
}
type ImportReceived struct {
Name string `json:"Name"`
Vcenter string `json:"Vcenter"`
VmId string `json:"VmId"`
InitialRam int `json:"InitialRam"`
PowerState int `json:"PowerState"`
CreationTime int `json:"CreationTime"`
InitialVcpus int `json:"InitialVcpus"`
ProvisionedDisk float64 `json:"ProvisionedDisk"`
Folder string `json:"Folder"`
ResourcePool string `json:"ResourcePool"`
Datacenter string `json:"Datacenter"`
Cluster string `json:"Cluster"`
}
type ConfigChangesReceived struct {
Modified string `json:"modified"`
}
// This probably needs more fields added so not in use yet
type ConfigSpec struct {
AlternateGuestName string `json:"AlternateGuestName"`
Annotation string `json:"Annotation"`
BootOptions any `json:"BootOptions"`
ChangeTrackingEnabled any `json:"ChangeTrackingEnabled"`
ChangeVersion string `json:"ChangeVersion"`
ConsolePreferences any `json:"ConsolePreferences"`
CPUAffinity any `json:"CpuAffinity"`
CPUAllocation any `json:"CpuAllocation"`
CPUFeatureMask any `json:"CpuFeatureMask"`
CPUHotAddEnabled any `json:"CpuHotAddEnabled"`
CPUHotRemoveEnabled any `json:"CpuHotRemoveEnabled"`
CreateDate string `json:"CreateDate"` // Modified from time.Time
Crypto any `json:"Crypto"`
DeviceChange []struct {
Backing any `json:"Backing"`
Device struct {
Backing *BackingSpec `json:"Backing,omitempty"`
CapacityInBytes int `json:"CapacityInBytes"`
CapacityInKB int `json:"CapacityInKB"`
Connectable struct {
AllowGuestControl bool `json:"AllowGuestControl"`
Connected bool `json:"Connected"`
MigrateConnect string `json:"MigrateConnect"`
StartConnected bool `json:"StartConnected"`
Status string `json:"Status"`
} `json:"Connectable"`
ControllerKey int `json:"ControllerKey"`
DeviceInfo struct {
Label string `json:"Label"`
Summary string `json:"Summary"`
} `json:"DeviceInfo"`
ExternalID string `json:"ExternalId"`
MacAddress string `json:"MacAddress"`
ResourceAllocation struct {
Limit int `json:"Limit"`
Reservation int `json:"Reservation"`
Share struct {
Level string `json:"Level"`
Shares int `json:"Shares"`
} `json:"Share"`
} `json:"ResourceAllocation"`
SlotInfo any `json:"SlotInfo"`
UnitNumber int `json:"UnitNumber"`
UptCompatibilityEnabled bool `json:"UptCompatibilityEnabled"`
WakeOnLanEnabled bool `json:"WakeOnLanEnabled"`
DiskObjectID string `json:"DiskObjectId"`
Iofilter any `json:"Iofilter"`
Key int `json:"Key"`
NativeUnmanagedLinkedClone any `json:"NativeUnmanagedLinkedClone"`
Shares any `json:"Shares"`
StorageIOAllocation struct {
Limit int `json:"Limit"`
Reservation any `json:"Reservation"`
Shares struct {
Level string `json:"Level"`
Shares int `json:"Shares"`
} `json:"Shares"`
} `json:"StorageIOAllocation"`
VDiskID any `json:"VDiskId"`
VFlashCacheConfigInfo any `json:"VFlashCacheConfigInfo"`
} `json:"Device,omitempty"`
FileOperation string `json:"FileOperation"`
Operation string `json:"Operation"`
Profile []struct {
ProfileData struct {
ExtensionKey string `json:"ExtensionKey"`
ObjectData string `json:"ObjectData"` // Modified from time.Time
} `json:"ProfileData"`
ProfileID string `json:"ProfileId"`
ProfileParams any `json:"ProfileParams"`
ReplicationSpec any `json:"ReplicationSpec"`
} `json:"Profile"`
} `json:"DeviceChange"`
ExtraConfig any `json:"ExtraConfig"`
Files struct {
FtMetadataDirectory string `json:"FtMetadataDirectory"`
LogDirectory string `json:"LogDirectory"`
SnapshotDirectory string `json:"SnapshotDirectory"`
SuspendDirectory string `json:"SuspendDirectory"`
VMPathName string `json:"VmPathName"`
} `json:"Files"`
Firmware string `json:"Firmware"`
Flags any `json:"Flags"`
FtInfo any `json:"FtInfo"`
GuestAutoLockEnabled any `json:"GuestAutoLockEnabled"`
GuestID string `json:"GuestId"`
GuestMonitoringModeInfo any `json:"GuestMonitoringModeInfo"`
InstanceUUID string `json:"InstanceUuid"`
LatencySensitivity any `json:"LatencySensitivity"`
LocationID string `json:"LocationId"`
ManagedBy any `json:"ManagedBy"`
MaxMksConnections int `json:"MaxMksConnections"`
MemoryAffinity any `json:"MemoryAffinity"`
MemoryAllocation any `json:"MemoryAllocation"`
MemoryHotAddEnabled any `json:"MemoryHotAddEnabled"`
MemoryMB int `json:"MemoryMB"`
MemoryReservationLockedToMax any `json:"MemoryReservationLockedToMax"`
MessageBusTunnelEnabled any `json:"MessageBusTunnelEnabled"`
MigrateEncryption string `json:"MigrateEncryption"`
Name string `json:"Name"`
NestedHVEnabled any `json:"NestedHVEnabled"`
NetworkShaper any `json:"NetworkShaper"`
NpivDesiredNodeWwns int `json:"NpivDesiredNodeWwns"`
NpivDesiredPortWwns int `json:"NpivDesiredPortWwns"`
NpivNodeWorldWideName any `json:"NpivNodeWorldWideName"`
NpivOnNonRdmDisks any `json:"NpivOnNonRdmDisks"`
NpivPortWorldWideName any `json:"NpivPortWorldWideName"`
NpivTemporaryDisabled any `json:"NpivTemporaryDisabled"`
NpivWorldWideNameOp string `json:"NpivWorldWideNameOp"`
NpivWorldWideNameType string `json:"NpivWorldWideNameType"`
NumCPUs int `json:"NumCPUs"`
NumCoresPerSocket int `json:"NumCoresPerSocket"`
PowerOpInfo any `json:"PowerOpInfo"`
RepConfig any `json:"RepConfig"`
ScheduledHardwareUpgradeInfo any `json:"ScheduledHardwareUpgradeInfo"`
SevEnabled any `json:"SevEnabled"`
SgxInfo any `json:"SgxInfo"`
SwapPlacement string `json:"SwapPlacement"`
Tools any `json:"Tools"`
UUID string `json:"Uuid"`
VAppConfig any `json:"VAppConfig"`
VAppConfigRemoved any `json:"VAppConfigRemoved"`
VAssertsEnabled any `json:"VAssertsEnabled"`
VPMCEnabled any `json:"VPMCEnabled"`
VcpuConfig any `json:"VcpuConfig"`
Version string `json:"Version"`
VirtualICH7MPresent any `json:"VirtualICH7MPresent"`
VirtualSMCPresent any `json:"VirtualSMCPresent"`
VMProfile any `json:"VmProfile"`
}
type BackingSpec struct {
Port struct {
ConnectionCookie int `json:"ConnectionCookie"`
PortKey string `json:"PortKey"`
PortgroupKey string `json:"PortgroupKey"`
SwitchUUID string `json:"SwitchUuid"`
} `json:"Port"`
BackingObjectID string `json:"BackingObjectId"`
ChangeID string `json:"ChangeId"`
ContentID string `json:"ContentId"`
Datastore struct {
Type string `json:"Type"`
Value string `json:"Value"`
} `json:"Datastore"`
DeltaDiskFormat string `json:"DeltaDiskFormat"`
DeltaDiskFormatVariant string `json:"DeltaDiskFormatVariant"`
DeltaGrainSize int `json:"DeltaGrainSize"`
DigestEnabled any `json:"DigestEnabled"`
DiskMode string `json:"DiskMode"`
EagerlyScrub bool `json:"EagerlyScrub"`
FileName string `json:"FileName"`
KeyID any `json:"KeyId"`
Parent any `json:"Parent"`
Sharing string `json:"Sharing"`
Split any `json:"Split"`
ThinProvisioned bool `json:"ThinProvisioned"`
UUID string `json:"Uuid"`
WriteThrough any `json:"WriteThrough"`
}

View File

@@ -4,11 +4,11 @@ import (
"log/slog"
"net/http"
"net/http/pprof"
"wnzl-snow/db"
"wnzl-snow/dist"
"wnzl-snow/internal/settings"
"wnzl-snow/server/handler"
"wnzl-snow/server/middleware"
"mocksnow/db"
"mocksnow/dist"
"mocksnow/internal/settings"
"mocksnow/server/handler"
"mocksnow/server/middleware"
)
func New(logger *slog.Logger, database db.Database, buildTime string, sha1ver string, goVersion string, settings *settings.Settings) http.Handler {