mirror of
https://github.com/Dvorinka/PPve.git
synced 2026-06-05 04:52:58 +00:00
Add files via upload
This commit is contained in:
+17
-22
@@ -710,6 +710,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Save banner
|
||||||
async function saveBanner(event) {
|
async function saveBanner(event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|
||||||
@@ -729,39 +730,33 @@
|
|||||||
formData.append('text', document.getElementById('bannerText').value);
|
formData.append('text', document.getElementById('bannerText').value);
|
||||||
formData.append('link', document.getElementById('bannerLink').value);
|
formData.append('link', document.getElementById('bannerLink').value);
|
||||||
|
|
||||||
// Create style object with default values
|
// Add style properties to form data with the correct format
|
||||||
const style = {
|
formData.append('style.backgroundColor', document.getElementById('bannerBgColor').value);
|
||||||
backgroundColor: document.getElementById('bannerBgColor').value,
|
formData.append('style.textColor', document.getElementById('bannerTextColor').value);
|
||||||
textColor: document.getElementById('bannerTextColor').value,
|
formData.append('style.textAlign', document.getElementById('bannerTextAlign').value);
|
||||||
textAlign: document.getElementById('bannerTextAlign').value,
|
formData.append('style.fontSize', document.getElementById('bannerFontSize').value);
|
||||||
fontSize: document.getElementById('bannerFontSize').value || '16px',
|
formData.append('style.padding', document.getElementById('bannerPadding').value);
|
||||||
padding: document.getElementById('bannerPadding').value || '0px',
|
formData.append('style.margin', document.getElementById('bannerMargin').value);
|
||||||
margin: document.getElementById('bannerMargin').value || '0px',
|
formData.append('style.borderRadius', document.getElementById('bannerBorderRadius').value);
|
||||||
borderRadius: document.getElementById('bannerBorderRadius').value || '0px',
|
formData.append('style.isVisible', document.getElementById('bannerVisible').checked);
|
||||||
isVisible: document.getElementById('bannerVisible').checked
|
|
||||||
};
|
|
||||||
|
|
||||||
// Convert style object to JSON string and append to form data
|
|
||||||
formData.append('style', JSON.stringify(style));
|
|
||||||
|
|
||||||
// Log form data for debugging
|
// Log form data for debugging
|
||||||
console.log('Odesílám data:');
|
console.log('Odesílám data:');
|
||||||
for (let [key, value] of formData.entries()) {
|
for (let [key, value] of formData.entries()) {
|
||||||
console.log(key, value);
|
console.log(key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create headers object
|
// Create a new headers object
|
||||||
const headers = {};
|
const headers = new Headers();
|
||||||
|
// Don't set Content-Type header manually when using FormData
|
||||||
|
// The browser will set it automatically with the correct boundary
|
||||||
|
|
||||||
// Add Authorization header if token exists
|
// Add Authorization header if token exists
|
||||||
const token = localStorage.getItem('token');
|
const token = localStorage.getItem('token');
|
||||||
if (token) {
|
if (token) {
|
||||||
headers['Authorization'] = `Bearer ${token}`;
|
headers.append('Authorization', `Bearer ${token}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Note: Don't set Content-Type header when using FormData with files
|
|
||||||
// The browser will set it automatically with the correct boundary
|
|
||||||
|
|
||||||
const response = await fetch('/api/banner/update', {
|
const response = await fetch('/api/banner/update', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: headers,
|
headers: headers,
|
||||||
@@ -1009,4 +1004,4 @@
|
|||||||
document.addEventListener('DOMContentLoaded', loadBanner);
|
document.addEventListener('DOMContentLoaded', loadBanner);
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+1
-1
@@ -128,4 +128,4 @@
|
|||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -156,20 +156,20 @@ func UpdateBannerHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
// Log form values for debugging
|
// Log form values for debugging
|
||||||
log.Printf("Form values: %+v", r.Form)
|
log.Printf("Form values: %+v", r.Form)
|
||||||
|
|
||||||
// Parse style as JSON string
|
// Create a new banner with default values
|
||||||
styleJSON := r.FormValue("style")
|
|
||||||
var style BannerStyle
|
|
||||||
if err := json.Unmarshal([]byte(styleJSON), &style); err != nil {
|
|
||||||
log.Printf("Error parsing style JSON: %v", err)
|
|
||||||
http.Error(w, "Error parsing style data: "+err.Error(), http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a new banner with parsed style
|
|
||||||
newBanner := BannerContent{
|
newBanner := BannerContent{
|
||||||
Text: r.FormValue("text"),
|
Text: r.FormValue("text"),
|
||||||
Link: r.FormValue("link"),
|
Link: r.FormValue("link"),
|
||||||
Style: style,
|
Style: BannerStyle{
|
||||||
|
BackgroundColor: r.FormValue("style[backgroundColor]"),
|
||||||
|
TextColor: r.FormValue("style[textColor]"),
|
||||||
|
TextAlign: r.FormValue("style[textAlign]"),
|
||||||
|
FontSize: r.FormValue("style[fontSize]"),
|
||||||
|
Padding: r.FormValue("style[padding]"),
|
||||||
|
Margin: r.FormValue("style[margin]"),
|
||||||
|
BorderRadius: r.FormValue("style[borderRadius]"),
|
||||||
|
IsVisible: r.FormValue("style[isVisible]") == "true",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log the banner data for debugging
|
// Log the banner data for debugging
|
||||||
|
|||||||
+22
-22
@@ -1,22 +1,22 @@
|
|||||||
# Makefile for kontakt service
|
# Makefile for kontakt service
|
||||||
.PHONY: dev run build clean
|
.PHONY: dev run build clean
|
||||||
|
|
||||||
PORT ?= 8081
|
PORT ?= 8081
|
||||||
BINARY_NAME := kontakt-service
|
BINARY_NAME := kontakt-service
|
||||||
BUILD_DIR := build
|
BUILD_DIR := build
|
||||||
|
|
||||||
##@ Development
|
##@ Development
|
||||||
dev: ## Run in development mode
|
dev: ## Run in development mode
|
||||||
@echo "Starting kontakt service..."
|
@echo "Starting kontakt service..."
|
||||||
@go run contact-scrape.go
|
@go run contact-scrape.go
|
||||||
|
|
||||||
run: build ## Run built binary
|
run: build ## Run built binary
|
||||||
@$(BUILD_DIR)/$(BINARY_NAME)
|
@$(BUILD_DIR)/$(BINARY_NAME)
|
||||||
|
|
||||||
build: ## Build the application
|
build: ## Build the application
|
||||||
@echo "Building kontakt service..."
|
@echo "Building kontakt service..."
|
||||||
@go build -o $(BUILD_DIR)/$(BINARY_NAME) contact-scrape.go
|
@go build -o $(BUILD_DIR)/$(BINARY_NAME) contact-scrape.go
|
||||||
|
|
||||||
clean: ## Clean build artifacts
|
clean: ## Clean build artifacts
|
||||||
@rm -rf $(BUILD_DIR)
|
@rm -rf $(BUILD_DIR)
|
||||||
@echo "Build artifacts removed"
|
@echo "Build artifacts removed"
|
||||||
+418
-418
@@ -1,418 +1,418 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/xuri/excelize/v2"
|
"github.com/xuri/excelize/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Contact struct {
|
type Contact struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Position string `json:"position"`
|
Position string `json:"position"`
|
||||||
Phone string `json:"phone,omitempty"`
|
Phone string `json:"phone,omitempty"`
|
||||||
ServicePhone string `json:"service_phone,omitempty"`
|
ServicePhone string `json:"service_phone,omitempty"`
|
||||||
Internal bool `json:"internal"`
|
Internal bool `json:"internal"`
|
||||||
PhoneFlap string `json:"phone_flap,omitempty"`
|
PhoneFlap string `json:"phone_flap,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ContactData struct {
|
type ContactData struct {
|
||||||
Contacts []Contact `json:"contacts"`
|
Contacts []Contact `json:"contacts"`
|
||||||
InternalContacts []Contact `json:"internal_contacts"`
|
InternalContacts []Contact `json:"internal_contacts"`
|
||||||
LastUpdated time.Time `json:"last_updated"`
|
LastUpdated time.Time `json:"last_updated"`
|
||||||
FileHash string `json:"file_hash"`
|
FileHash string `json:"file_hash"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
currentData *ContactData
|
currentData *ContactData
|
||||||
dataFile = "data/contacts.json"
|
dataFile = "data/contacts.json"
|
||||||
xlsxFile = "/mnt/telefony/TelefonniSeznamWeb.xlsx"
|
xlsxFile = "/mnt/telefony/TelefonniSeznamWeb.xlsx"
|
||||||
)
|
)
|
||||||
|
|
||||||
func startAutoReload() {
|
func startAutoReload() {
|
||||||
ticker := time.NewTicker(1 * time.Hour)
|
ticker := time.NewTicker(1 * time.Hour)
|
||||||
quit := make(chan struct{})
|
quit := make(chan struct{})
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
log.Println("Auto-reloading contact data...")
|
log.Println("Auto-reloading contact data...")
|
||||||
loadData()
|
loadData()
|
||||||
case <-quit:
|
case <-quit:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Create data directory if it doesn't exist
|
// Create data directory if it doesn't exist
|
||||||
if err := os.MkdirAll("data", 0755); err != nil {
|
if err := os.MkdirAll("data", 0755); err != nil {
|
||||||
log.Printf("Warning: Could not create data directory: %v", err)
|
log.Printf("Warning: Could not create data directory: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start auto-reload scheduler
|
// Start auto-reload scheduler
|
||||||
startAutoReload()
|
startAutoReload()
|
||||||
|
|
||||||
// Load existing data or parse from Excel
|
// Load existing data or parse from Excel
|
||||||
loadData()
|
loadData()
|
||||||
|
|
||||||
// Set up HTTP handlers
|
// Set up HTTP handlers
|
||||||
http.HandleFunc("/", serveIndex)
|
http.HandleFunc("/", serveIndex)
|
||||||
http.HandleFunc("/contacts", serveContacts)
|
http.HandleFunc("/contacts", serveContacts)
|
||||||
http.HandleFunc("/reload", reloadData)
|
http.HandleFunc("/reload", reloadData)
|
||||||
|
|
||||||
// Start server
|
// Start server
|
||||||
port := os.Getenv("PORT")
|
port := os.Getenv("PORT")
|
||||||
if port == "" {
|
if port == "" {
|
||||||
port = "80"
|
port = "80"
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("Server starting on port %s", port)
|
log.Printf("Server starting on port %s", port)
|
||||||
log.Printf("Access the application at: http://webportal:%s", port)
|
log.Printf("Access the application at: http://webportal:%s", port)
|
||||||
log.Fatal(http.ListenAndServe(":"+port, nil))
|
log.Fatal(http.ListenAndServe(":"+port, nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadData() {
|
func loadData() {
|
||||||
// Check if Excel file exists
|
// Check if Excel file exists
|
||||||
if _, err := os.Stat(xlsxFile); os.IsNotExist(err) {
|
if _, err := os.Stat(xlsxFile); os.IsNotExist(err) {
|
||||||
log.Printf("Excel file %s not found, using empty data", xlsxFile)
|
log.Printf("Excel file %s not found, using empty data", xlsxFile)
|
||||||
currentData = &ContactData{
|
currentData = &ContactData{
|
||||||
Contacts: []Contact{},
|
Contacts: []Contact{},
|
||||||
InternalContacts: []Contact{},
|
InternalContacts: []Contact{},
|
||||||
LastUpdated: time.Now(),
|
LastUpdated: time.Now(),
|
||||||
FileHash: "",
|
FileHash: "",
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate current file hash
|
// Calculate current file hash
|
||||||
currentHash, err := calculateFileHash(xlsxFile)
|
currentHash, err := calculateFileHash(xlsxFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error calculating file hash: %v", err)
|
log.Printf("Error calculating file hash: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if cached data exists and is up to date
|
// Check if cached data exists and is up to date
|
||||||
if cachedData, err := loadCachedData(); err == nil {
|
if cachedData, err := loadCachedData(); err == nil {
|
||||||
if cachedData.FileHash == currentHash {
|
if cachedData.FileHash == currentHash {
|
||||||
log.Println("Using cached data (file unchanged)")
|
log.Println("Using cached data (file unchanged)")
|
||||||
currentData = cachedData
|
currentData = cachedData
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse Excel file
|
// Parse Excel file
|
||||||
log.Println("Parsing Excel file...")
|
log.Println("Parsing Excel file...")
|
||||||
contacts, err := parseExcelFile(xlsxFile)
|
contacts, err := parseExcelFile(xlsxFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error parsing Excel file: %v", err)
|
log.Printf("Error parsing Excel file: %v", err)
|
||||||
// Use empty data if parsing fails
|
// Use empty data if parsing fails
|
||||||
currentData = &ContactData{
|
currentData = &ContactData{
|
||||||
Contacts: []Contact{},
|
Contacts: []Contact{},
|
||||||
InternalContacts: []Contact{},
|
InternalContacts: []Contact{},
|
||||||
LastUpdated: time.Now(),
|
LastUpdated: time.Now(),
|
||||||
FileHash: currentHash,
|
FileHash: currentHash,
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
currentData = processContacts(contacts)
|
currentData = processContacts(contacts)
|
||||||
currentData.FileHash = currentHash
|
currentData.FileHash = currentHash
|
||||||
|
|
||||||
// Save to cache
|
// Save to cache
|
||||||
if err := saveCachedData(currentData); err != nil {
|
if err := saveCachedData(currentData); err != nil {
|
||||||
log.Printf("Warning: Could not save cached data: %v", err)
|
log.Printf("Warning: Could not save cached data: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("Loaded %d contacts from Excel file", len(currentData.Contacts)+len(currentData.InternalContacts))
|
log.Printf("Loaded %d contacts from Excel file", len(currentData.Contacts)+len(currentData.InternalContacts))
|
||||||
}
|
}
|
||||||
|
|
||||||
func calculateFileHash(filename string) (string, error) {
|
func calculateFileHash(filename string) (string, error) {
|
||||||
file, err := os.Open(filename)
|
file, err := os.Open(filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
|
||||||
hash := md5.New()
|
hash := md5.New()
|
||||||
if _, err := io.Copy(hash, file); err != nil {
|
if _, err := io.Copy(hash, file); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
return fmt.Sprintf("%x", hash.Sum(nil)), nil
|
return fmt.Sprintf("%x", hash.Sum(nil)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadCachedData() (*ContactData, error) {
|
func loadCachedData() (*ContactData, error) {
|
||||||
file, err := os.Open(dataFile)
|
file, err := os.Open(dataFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
|
||||||
var data ContactData
|
var data ContactData
|
||||||
decoder := json.NewDecoder(file)
|
decoder := json.NewDecoder(file)
|
||||||
if err := decoder.Decode(&data); err != nil {
|
if err := decoder.Decode(&data); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &data, nil
|
return &data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func saveCachedData(data *ContactData) error {
|
func saveCachedData(data *ContactData) error {
|
||||||
file, err := os.Create(dataFile)
|
file, err := os.Create(dataFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
|
||||||
encoder := json.NewEncoder(file)
|
encoder := json.NewEncoder(file)
|
||||||
encoder.SetIndent("", " ")
|
encoder.SetIndent("", " ")
|
||||||
return encoder.Encode(data)
|
return encoder.Encode(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseExcelFile(filename string) ([]Contact, error) {
|
func parseExcelFile(filename string) ([]Contact, error) {
|
||||||
f, err := excelize.OpenFile(filename)
|
f, err := excelize.OpenFile(filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to open Excel file: %v", err)
|
return nil, fmt.Errorf("failed to open Excel file: %v", err)
|
||||||
}
|
}
|
||||||
defer f.Close()
|
defer f.Close()
|
||||||
|
|
||||||
// Get the first sheet name
|
// Get the first sheet name
|
||||||
sheets := f.GetSheetList()
|
sheets := f.GetSheetList()
|
||||||
if len(sheets) == 0 {
|
if len(sheets) == 0 {
|
||||||
return nil, fmt.Errorf("no sheets found in Excel file")
|
return nil, fmt.Errorf("no sheets found in Excel file")
|
||||||
}
|
}
|
||||||
|
|
||||||
sheetName := sheets[0]
|
sheetName := sheets[0]
|
||||||
|
|
||||||
// Parse the single table (columns A-E)
|
// Parse the single table (columns A-E)
|
||||||
contacts := parseTable(f, sheetName, "A", "E")
|
contacts := parseTable(f, sheetName, "A", "E")
|
||||||
return contacts, nil
|
return contacts, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseTable(f *excelize.File, sheetName, startCol, endCol string) []Contact {
|
func parseTable(f *excelize.File, sheetName, startCol, endCol string) []Contact {
|
||||||
var contacts []Contact
|
var contacts []Contact
|
||||||
|
|
||||||
// Get all rows in the sheet
|
// Get all rows in the sheet
|
||||||
rows, err := f.GetRows(sheetName)
|
rows, err := f.GetRows(sheetName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error getting rows: %v", err)
|
log.Printf("Error getting rows: %v", err)
|
||||||
return contacts
|
return contacts
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip first 3 and last 3 lines
|
// Skip first 3 and last 3 lines
|
||||||
startRow := 3
|
startRow := 3
|
||||||
endRow := len(rows) - 3
|
endRow := len(rows) - 3
|
||||||
if endRow <= startRow {
|
if endRow <= startRow {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Column indices
|
// Column indices
|
||||||
const (
|
const (
|
||||||
nameCol = 0
|
nameCol = 0
|
||||||
positionCol = 1
|
positionCol = 1
|
||||||
phoneCol = 2
|
phoneCol = 2
|
||||||
servicePhoneCol = 3
|
servicePhoneCol = 3
|
||||||
flapCol = 4
|
flapCol = 4
|
||||||
)
|
)
|
||||||
|
|
||||||
for i := startRow; i < endRow; i++ {
|
for i := startRow; i < endRow; i++ {
|
||||||
row := rows[i]
|
row := rows[i]
|
||||||
|
|
||||||
// Skip if row is too short
|
// Skip if row is too short
|
||||||
if len(row) <= nameCol {
|
if len(row) <= nameCol {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for "Aktualizace" - end of data
|
// Check for "Aktualizace" - end of data
|
||||||
if len(row) > nameCol && strings.Contains(strings.ToLower(row[nameCol]), "aktualizace") {
|
if len(row) > nameCol && strings.Contains(strings.ToLower(row[nameCol]), "aktualizace") {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
contact := Contact{
|
contact := Contact{
|
||||||
Name: strings.TrimSpace(row[nameCol]),
|
Name: strings.TrimSpace(row[nameCol]),
|
||||||
Position: safeGet(row, positionCol, ""),
|
Position: safeGet(row, positionCol, ""),
|
||||||
Phone: formatPhoneNumber(safeGet(row, phoneCol, "")),
|
Phone: formatPhoneNumber(safeGet(row, phoneCol, "")),
|
||||||
ServicePhone: formatPhoneNumber(safeGet(row, servicePhoneCol, "")), // Full mobile number
|
ServicePhone: formatPhoneNumber(safeGet(row, servicePhoneCol, "")), // Full mobile number
|
||||||
PhoneFlap: formatPhoneFlap(safeGet(row, flapCol, "")), // Internal extension with *
|
PhoneFlap: formatPhoneFlap(safeGet(row, flapCol, "")), // Internal extension with *
|
||||||
}
|
}
|
||||||
|
|
||||||
contacts = append(contacts, contact)
|
contacts = append(contacts, contact)
|
||||||
}
|
}
|
||||||
|
|
||||||
return contacts
|
return contacts
|
||||||
}
|
}
|
||||||
|
|
||||||
func safeGet(row []string, index int, defaultValue string) string {
|
func safeGet(row []string, index int, defaultValue string) string {
|
||||||
if index < len(row) {
|
if index < len(row) {
|
||||||
return row[index]
|
return row[index]
|
||||||
}
|
}
|
||||||
return defaultValue
|
return defaultValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func formatPhoneNumber(phone string) string {
|
func formatPhoneNumber(phone string) string {
|
||||||
if phone == "" {
|
if phone == "" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove extra whitespace
|
// Remove extra whitespace
|
||||||
phone = strings.TrimSpace(phone)
|
phone = strings.TrimSpace(phone)
|
||||||
|
|
||||||
// Remove common formatting characters
|
// Remove common formatting characters
|
||||||
re := regexp.MustCompile(`[^\d+\-\s()]`)
|
re := regexp.MustCompile(`[^\d+\-\s()]`)
|
||||||
phone = re.ReplaceAllString(phone, "")
|
phone = re.ReplaceAllString(phone, "")
|
||||||
|
|
||||||
// If it's just a short number (internal extension), keep as is
|
// If it's just a short number (internal extension), keep as is
|
||||||
if len(phone) <= 3 {
|
if len(phone) <= 3 {
|
||||||
return phone
|
return phone
|
||||||
}
|
}
|
||||||
|
|
||||||
// If it looks like a Czech number without country code, add it
|
// If it looks like a Czech number without country code, add it
|
||||||
if regexp.MustCompile(`^[67]\d{8}$`).MatchString(strings.ReplaceAll(phone, " ", "")) {
|
if regexp.MustCompile(`^[67]\d{8}$`).MatchString(strings.ReplaceAll(phone, " ", "")) {
|
||||||
return "+420 " + phone
|
return "+420 " + phone
|
||||||
}
|
}
|
||||||
|
|
||||||
return phone
|
return phone
|
||||||
}
|
}
|
||||||
|
|
||||||
func formatPhoneFlap(flap string) string {
|
func formatPhoneFlap(flap string) string {
|
||||||
flap = strings.TrimSpace(flap)
|
flap = strings.TrimSpace(flap)
|
||||||
if flap == "" {
|
if flap == "" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
if !strings.HasPrefix(flap, "*") {
|
if !strings.HasPrefix(flap, "*") {
|
||||||
return "*" + flap
|
return "*" + flap
|
||||||
}
|
}
|
||||||
return flap
|
return flap
|
||||||
}
|
}
|
||||||
|
|
||||||
func processContacts(contacts []Contact) *ContactData {
|
func processContacts(contacts []Contact) *ContactData {
|
||||||
var data ContactData
|
var data ContactData
|
||||||
data.Contacts = []Contact{}
|
data.Contacts = []Contact{}
|
||||||
data.InternalContacts = []Contact{}
|
data.InternalContacts = []Contact{}
|
||||||
|
|
||||||
for _, contact := range contacts {
|
for _, contact := range contacts {
|
||||||
// Trim whitespace and check for "Interní"
|
// Trim whitespace and check for "Interní"
|
||||||
if strings.TrimSpace(contact.Position) == "Interní" {
|
if strings.TrimSpace(contact.Position) == "Interní" {
|
||||||
contact.Internal = true
|
contact.Internal = true
|
||||||
data.InternalContacts = append(data.InternalContacts, contact)
|
data.InternalContacts = append(data.InternalContacts, contact)
|
||||||
} else {
|
} else {
|
||||||
contact.Internal = false
|
contact.Internal = false
|
||||||
data.Contacts = append(data.Contacts, contact)
|
data.Contacts = append(data.Contacts, contact)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
data.LastUpdated = time.Now()
|
data.LastUpdated = time.Now()
|
||||||
return &data
|
return &data
|
||||||
}
|
}
|
||||||
|
|
||||||
func serveIndex(w http.ResponseWriter, r *http.Request) {
|
func serveIndex(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.URL.Path != "/" {
|
if r.URL.Path != "/" {
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if index.html exists
|
// Check if index.html exists
|
||||||
if _, err := os.Stat("index.html"); os.IsNotExist(err) {
|
if _, err := os.Stat("index.html"); os.IsNotExist(err) {
|
||||||
// Serve embedded HTML if file doesn't exist
|
// Serve embedded HTML if file doesn't exist
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
fmt.Fprint(w, getEmbeddedHTML())
|
fmt.Fprint(w, getEmbeddedHTML())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
http.ServeFile(w, r, "index.html")
|
http.ServeFile(w, r, "index.html")
|
||||||
}
|
}
|
||||||
|
|
||||||
func serveContacts(w http.ResponseWriter, r *http.Request) {
|
func serveContacts(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
|
|
||||||
if currentData == nil {
|
if currentData == nil {
|
||||||
http.Error(w, `{"error": "No data available"}`, http.StatusInternalServerError)
|
http.Error(w, `{"error": "No data available"}`, http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
encoder := json.NewEncoder(w)
|
encoder := json.NewEncoder(w)
|
||||||
encoder.SetIndent("", " ")
|
encoder.SetIndent("", " ")
|
||||||
encoder.Encode(currentData)
|
encoder.Encode(currentData)
|
||||||
}
|
}
|
||||||
|
|
||||||
func reloadData(w http.ResponseWriter, r *http.Request) {
|
func reloadData(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != "POST" {
|
if r.Method != "POST" {
|
||||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Println("Manual reload requested")
|
log.Println("Manual reload requested")
|
||||||
loadData()
|
loadData()
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
fmt.Fprintf(w, `{"status": "reloaded", "contacts_count": %d}`, len(currentData.Contacts)+len(currentData.InternalContacts))
|
fmt.Fprintf(w, `{"status": "reloaded", "contacts_count": %d}`, len(currentData.Contacts)+len(currentData.InternalContacts))
|
||||||
}
|
}
|
||||||
|
|
||||||
func getEmbeddedHTML() string {
|
func getEmbeddedHTML() string {
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html lang="cs">
|
<html lang="cs">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Kontakty</title>
|
<title>Kontakty</title>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
|
||||||
</head>
|
</head>
|
||||||
<body class="bg-gray-100 min-h-screen">
|
<body class="bg-gray-100 min-h-screen">
|
||||||
<header class="bg-gradient-to-r from-blue-600 to-indigo-700 text-white shadow-lg">
|
<header class="bg-gradient-to-r from-blue-600 to-indigo-700 text-white shadow-lg">
|
||||||
<div class="container mx-auto px-4 py-6">
|
<div class="container mx-auto px-4 py-6">
|
||||||
<h1 class="text-3xl font-bold">📞 Firemní telefonní seznam</h1>
|
<h1 class="text-3xl font-bold">📞 Firemní telefonní seznam</h1>
|
||||||
<p class="mt-2 text-blue-100">Poppe + Potthoff kontakty</p>
|
<p class="mt-2 text-blue-100">Poppe + Potthoff kontakty</p>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class="container mx-auto px-4 py-8 max-w-7xl">
|
<div class="container mx-auto px-4 py-8 max-w-7xl">
|
||||||
<div class="bg-white rounded-xl shadow p-6 md:p-8">
|
<div class="bg-white rounded-xl shadow p-6 md:p-8">
|
||||||
<div class="flex justify-between items-center mb-6">
|
<div class="flex justify-between items-center mb-6">
|
||||||
<button onclick="reloadContacts()" id="reloadBtn"
|
<button onclick="reloadContacts()" id="reloadBtn"
|
||||||
class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-all duration-200 shadow-md hover:shadow-lg flex items-center gap-2">
|
class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-all duration-200 shadow-md hover:shadow-lg flex items-center gap-2">
|
||||||
<i class="fas fa-sync-alt"></i>
|
<i class="fas fa-sync-alt"></i>
|
||||||
Obnovit
|
Obnovit
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-6">
|
<div class="mb-6">
|
||||||
<div class="relative">
|
<div class="relative">
|
||||||
<input type="text" id="searchInput" placeholder="Hledat podle jména, pozice nebo telefonu..."
|
<input type="text" id="searchInput" placeholder="Hledat podle jména, pozice nebo telefonu..."
|
||||||
class="w-full px-4 py-3 pl-12 rounded-lg shadow-sm border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none text-lg"
|
class="w-full px-4 py-3 pl-12 rounded-lg shadow-sm border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none text-lg"
|
||||||
onkeyup="filterContacts()">
|
onkeyup="filterContacts()">
|
||||||
<i class="fas fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
|
<i class="fas fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="loading" class="text-center py-16">
|
<div id="loading" class="text-center py-16">
|
||||||
<div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
|
<div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
|
||||||
<p class="text-gray-600 text-lg">Načítání kontaktů...</p>
|
<p class="text-gray-600 text-lg">Načítání kontaktů...</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="contactsList" class="hidden">
|
<div id="contactsList" class="hidden">
|
||||||
<div id="stats" class="mb-6 p-4 bg-gray-50 rounded-lg border text-sm text-gray-700"></div>
|
<div id="stats" class="mb-6 p-4 bg-gray-50 rounded-lg border text-sm text-gray-700"></div>
|
||||||
<div id="contacts" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"></div>
|
<div id="contacts" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<footer class="bg-gray-800 text-gray-400 py-6 mt-12">
|
<footer class="bg-gray-800 text-gray-400 py-6 mt-12">
|
||||||
<div class="container mx-auto px-4 text-center">
|
<div class="container mx-auto px-4 text-center">
|
||||||
<p> 2025 Poppe + Potthoff</p>
|
<p> 2025 Poppe + Potthoff</p>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>`
|
</html>`
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user