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:
@@ -1,481 +1,485 @@
|
|||||||
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"`
|
||||||
Table int `json:"table"` // 1 for first table, 2 for second table
|
Table int `json:"table"` // 1 for first table, 2 for second table
|
||||||
}
|
}
|
||||||
|
|
||||||
type ContactData struct {
|
type ContactData struct {
|
||||||
Contacts []Contact `json:"contacts"`
|
Contacts []Contact `json:"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 = "contacts.xlsx"
|
xlsxFile = "contacts.xlsx"
|
||||||
)
|
)
|
||||||
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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://localhost:%s", port)
|
log.Printf("Access the application at: http://localhost:%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{},
|
||||||
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{},
|
||||||
LastUpdated: time.Now(),
|
LastUpdated: time.Now(),
|
||||||
FileHash: currentHash,
|
FileHash: currentHash,
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
currentData = &ContactData{
|
currentData = &ContactData{
|
||||||
Contacts: contacts,
|
Contacts: contacts,
|
||||||
LastUpdated: time.Now(),
|
LastUpdated: time.Now(),
|
||||||
FileHash: currentHash,
|
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(contacts))
|
log.Printf("Loaded %d contacts from Excel file", len(contacts))
|
||||||
}
|
}
|
||||||
|
|
||||||
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]
|
||||||
var contacts []Contact
|
var contacts []Contact
|
||||||
|
|
||||||
// Parse first table (A-D columns)
|
// Parse first table (A-D columns)
|
||||||
contacts = append(contacts, parseTable(f, sheetName, "A", "D", 1)...)
|
contacts = append(contacts, parseTable(f, sheetName, "A", "D", 1)...)
|
||||||
|
|
||||||
// Parse second table (F-H columns)
|
// Parse second table (F-H columns)
|
||||||
contacts = append(contacts, parseTable(f, sheetName, "F", "H", 2)...)
|
contacts = append(contacts, parseTable(f, sheetName, "F", "H", 2)...)
|
||||||
|
|
||||||
return contacts, nil
|
return contacts, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseTable(f *excelize.File, sheetName, startCol, endCol string, tableNum int) []Contact {
|
func parseTable(f *excelize.File, sheetName, startCol, endCol string, tableNum int) []Contact {
|
||||||
var contacts []Contact
|
var contacts []Contact
|
||||||
var currentContact *Contact
|
var currentContact *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 header rows (first 3 rows based on your description)
|
// Skip header rows (first 3 rows based on your description)
|
||||||
startRow := 3
|
startRow := 3
|
||||||
if len(rows) <= startRow {
|
if len(rows) <= startRow {
|
||||||
return contacts
|
return contacts
|
||||||
}
|
}
|
||||||
|
|
||||||
// Column indices
|
// Column indices
|
||||||
var nameCol, positionCol, phoneCol, servicePhoneCol int
|
var nameCol, positionCol, phoneCol, servicePhoneCol int
|
||||||
if tableNum == 1 {
|
if tableNum == 1 {
|
||||||
nameCol, positionCol, phoneCol, servicePhoneCol = 0, 1, 2, 3 // A, B, C, D
|
nameCol, positionCol, phoneCol, servicePhoneCol = 0, 1, 2, 3 // A, B, C, D
|
||||||
} else {
|
} else {
|
||||||
nameCol, positionCol, phoneCol = 5, 6, 7 // F, G, H
|
nameCol, positionCol, phoneCol = 5, 6, 7 // F, G, H
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := startRow; i < len(rows); i++ {
|
for i := startRow; i < len(rows); 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
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for special formatting rows (like "*02(xx)")
|
// Check for special formatting rows (like "*02(xx)")
|
||||||
if len(row) > positionCol && strings.Contains(row[positionCol], "*") {
|
if len(row) > positionCol && strings.Contains(row[positionCol], "*") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
name := strings.TrimSpace(row[nameCol])
|
name := strings.TrimSpace(row[nameCol])
|
||||||
position := ""
|
position := ""
|
||||||
phone := ""
|
phone := ""
|
||||||
servicePhone := ""
|
servicePhone := ""
|
||||||
|
|
||||||
if len(row) > positionCol {
|
if len(row) > positionCol {
|
||||||
position = strings.TrimSpace(row[positionCol])
|
position = strings.TrimSpace(row[positionCol])
|
||||||
}
|
}
|
||||||
if len(row) > phoneCol {
|
if len(row) > phoneCol {
|
||||||
phone = strings.TrimSpace(row[phoneCol])
|
phone = strings.TrimSpace(row[phoneCol])
|
||||||
}
|
}
|
||||||
if tableNum == 1 && len(row) > servicePhoneCol {
|
if tableNum == 1 && len(row) > servicePhoneCol {
|
||||||
servicePhone = strings.TrimSpace(row[servicePhoneCol])
|
servicePhone = strings.TrimSpace(row[servicePhoneCol])
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clean phone numbers
|
// Clean phone numbers
|
||||||
phone = cleanPhoneNumber(phone)
|
phone = cleanPhoneNumber(phone)
|
||||||
servicePhone = cleanPhoneNumber(servicePhone)
|
servicePhone = cleanPhoneNumber(servicePhone)
|
||||||
|
|
||||||
// If we have a name, start a new contact
|
// If we have a name, start a new contact
|
||||||
if name != "" && !strings.Contains(name, "(") {
|
if name != "" && !strings.Contains(name, "(") {
|
||||||
currentContact = &Contact{
|
currentContact = &Contact{
|
||||||
Name: name,
|
Name: name,
|
||||||
Position: position,
|
Position: position,
|
||||||
Phone: phone,
|
Phone: phone,
|
||||||
ServicePhone: servicePhone,
|
ServicePhone: servicePhone,
|
||||||
Table: tableNum,
|
Table: tableNum,
|
||||||
}
|
}
|
||||||
contacts = append(contacts, *currentContact)
|
contacts = append(contacts, *currentContact)
|
||||||
} else if currentContact != nil {
|
} else if currentContact != nil && !strings.HasPrefix(row[nameCol], "Aktualizace dne") {
|
||||||
// This is additional data for the current contact
|
// Skip general contacts that don't have names
|
||||||
newContact := *currentContact
|
if strings.Contains(row[nameCol], "převzetí hovoru") || strings.Contains(row[nameCol], "hlavní vchod") || strings.Contains(row[nameCol], "brána") {
|
||||||
if position != "" {
|
continue
|
||||||
newContact.Position = position
|
}
|
||||||
}
|
// This is additional data for the current contact
|
||||||
if phone != "" {
|
newContact := *currentContact
|
||||||
newContact.Phone = phone
|
if position != "" {
|
||||||
}
|
newContact.Position = position
|
||||||
if servicePhone != "" {
|
}
|
||||||
newContact.ServicePhone = servicePhone
|
if phone != "" {
|
||||||
}
|
newContact.Phone = phone
|
||||||
contacts = append(contacts, newContact)
|
}
|
||||||
}
|
if servicePhone != "" {
|
||||||
}
|
newContact.ServicePhone = servicePhone
|
||||||
|
}
|
||||||
return contacts
|
contacts = append(contacts, newContact)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
func cleanPhoneNumber(phone string) string {
|
|
||||||
if phone == "" {
|
return contacts
|
||||||
return ""
|
}
|
||||||
}
|
|
||||||
|
func cleanPhoneNumber(phone string) string {
|
||||||
// Remove extra whitespace
|
if phone == "" {
|
||||||
phone = strings.TrimSpace(phone)
|
return ""
|
||||||
|
}
|
||||||
// Remove common formatting characters
|
|
||||||
re := regexp.MustCompile(`[^\d+\-\s()]`)
|
// Remove extra whitespace
|
||||||
phone = re.ReplaceAllString(phone, "")
|
phone = strings.TrimSpace(phone)
|
||||||
|
|
||||||
// If it's just a short number (internal extension), keep as is
|
// Remove common formatting characters
|
||||||
if len(phone) <= 3 {
|
re := regexp.MustCompile(`[^\d+\-\s()]`)
|
||||||
return phone
|
phone = re.ReplaceAllString(phone, "")
|
||||||
}
|
|
||||||
|
// If it's just a short number (internal extension), keep as is
|
||||||
// If it looks like a Czech number without country code, add it
|
if len(phone) <= 3 {
|
||||||
if regexp.MustCompile(`^[67]\d{8}$`).MatchString(strings.ReplaceAll(phone, " ", "")) {
|
return phone
|
||||||
return "+420 " + phone
|
}
|
||||||
}
|
|
||||||
|
// If it looks like a Czech number without country code, add it
|
||||||
return phone
|
if regexp.MustCompile(`^[67]\d{8}$`).MatchString(strings.ReplaceAll(phone, " ", "")) {
|
||||||
}
|
return "+420 " + phone
|
||||||
|
}
|
||||||
func serveIndex(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.URL.Path != "/" {
|
return phone
|
||||||
http.NotFound(w, r)
|
}
|
||||||
return
|
|
||||||
}
|
func serveIndex(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/" {
|
||||||
// Check if index.html exists
|
http.NotFound(w, r)
|
||||||
if _, err := os.Stat("index.html"); os.IsNotExist(err) {
|
return
|
||||||
// Serve embedded HTML if file doesn't exist
|
}
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
||||||
fmt.Fprint(w, getEmbeddedHTML())
|
// Check if index.html exists
|
||||||
return
|
if _, err := os.Stat("index.html"); os.IsNotExist(err) {
|
||||||
}
|
// Serve embedded HTML if file doesn't exist
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
http.ServeFile(w, r, "index.html")
|
fmt.Fprint(w, getEmbeddedHTML())
|
||||||
}
|
return
|
||||||
|
}
|
||||||
func serveContacts(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
http.ServeFile(w, r, "index.html")
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
}
|
||||||
|
|
||||||
if currentData == nil {
|
func serveContacts(w http.ResponseWriter, r *http.Request) {
|
||||||
http.Error(w, `{"error": "No data available"}`, http.StatusInternalServerError)
|
w.Header().Set("Content-Type", "application/json")
|
||||||
return
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
}
|
|
||||||
|
if currentData == nil {
|
||||||
encoder := json.NewEncoder(w)
|
http.Error(w, `{"error": "No data available"}`, http.StatusInternalServerError)
|
||||||
encoder.SetIndent("", " ")
|
return
|
||||||
encoder.Encode(currentData)
|
}
|
||||||
}
|
|
||||||
|
encoder := json.NewEncoder(w)
|
||||||
func reloadData(w http.ResponseWriter, r *http.Request) {
|
encoder.SetIndent("", " ")
|
||||||
if r.Method != "POST" {
|
encoder.Encode(currentData)
|
||||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
}
|
||||||
return
|
|
||||||
}
|
func reloadData(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != "POST" {
|
||||||
log.Println("Manual reload requested")
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
loadData()
|
return
|
||||||
|
}
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
fmt.Fprintf(w, `{"status": "reloaded", "contacts_count": %d}`, len(currentData.Contacts))
|
log.Println("Manual reload requested")
|
||||||
}
|
loadData()
|
||||||
|
|
||||||
func getEmbeddedHTML() string {
|
w.Header().Set("Content-Type", "application/json")
|
||||||
return `<!DOCTYPE html>
|
fmt.Fprintf(w, `{"status": "reloaded", "contacts_count": %d}`, len(currentData.Contacts))
|
||||||
<html lang="cs">
|
}
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
func getEmbeddedHTML() string {
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
return `<!DOCTYPE html>
|
||||||
<title>Kontakty</title>
|
<html lang="cs">
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<head>
|
||||||
</head>
|
<meta charset="UTF-8">
|
||||||
<body class="bg-gray-50 min-h-screen">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<div class="container mx-auto px-4 py-8">
|
<title>Kontakty</title>
|
||||||
<div class="bg-white rounded-lg shadow-lg p-6">
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
<div class="flex justify-between items-center mb-6">
|
</head>
|
||||||
<h1 class="text-3xl font-bold text-gray-800">Kontakty</h1>
|
<body class="bg-gray-50 min-h-screen">
|
||||||
<button onclick="reloadContacts()" id="reloadBtn"
|
<div class="container mx-auto px-4 py-8">
|
||||||
class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors">
|
<div class="bg-white rounded-lg shadow-lg p-6">
|
||||||
Obnovit
|
<div class="flex justify-between items-center mb-6">
|
||||||
</button>
|
<h1 class="text-3xl font-bold text-gray-800">Kontakty</h1>
|
||||||
</div>
|
<button onclick="reloadContacts()" id="reloadBtn"
|
||||||
|
class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors">
|
||||||
<div class="mb-4">
|
Obnovit
|
||||||
<input type="text" id="searchInput" placeholder="Hledat kontakt..."
|
</button>
|
||||||
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
</div>
|
||||||
onkeyup="filterContacts()">
|
|
||||||
</div>
|
<div class="mb-4">
|
||||||
|
<input type="text" id="searchInput" placeholder="Hledat kontakt..."
|
||||||
<div id="loading" class="text-center py-8">
|
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||||
<div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
|
onkeyup="filterContacts()">
|
||||||
<p class="mt-2 text-gray-600">Načítání kontaktů...</p>
|
</div>
|
||||||
</div>
|
|
||||||
|
<div id="loading" class="text-center py-8">
|
||||||
<div id="contactsList" class="hidden">
|
<div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
|
||||||
<div id="stats" class="mb-4 text-sm text-gray-600"></div>
|
<p class="mt-2 text-gray-600">Načítání kontaktů...</p>
|
||||||
<div id="contacts" class="grid gap-4 md:grid-cols-2 lg:grid-cols-3"></div>
|
</div>
|
||||||
</div>
|
|
||||||
|
<div id="contactsList" class="hidden">
|
||||||
<div id="error" class="hidden text-center py-8 text-red-600"></div>
|
<div id="stats" class="mb-4 text-sm text-gray-600"></div>
|
||||||
</div>
|
<div id="contacts" class="grid gap-4 md:grid-cols-2 lg:grid-cols-3"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<div id="error" class="hidden text-center py-8 text-red-600"></div>
|
||||||
let allContacts = [];
|
</div>
|
||||||
let filteredContacts = [];
|
</div>
|
||||||
|
|
||||||
async function loadContacts() {
|
<script>
|
||||||
try {
|
let allContacts = [];
|
||||||
const response = await fetch('/contacts');
|
let filteredContacts = [];
|
||||||
const data = await response.json();
|
|
||||||
allContacts = data.contacts || [];
|
async function loadContacts() {
|
||||||
filteredContacts = [...allContacts];
|
try {
|
||||||
|
const response = await fetch('/contacts');
|
||||||
document.getElementById('loading').classList.add('hidden');
|
const data = await response.json();
|
||||||
document.getElementById('contactsList').classList.remove('hidden');
|
allContacts = data.contacts || [];
|
||||||
|
filteredContacts = [...allContacts];
|
||||||
updateStats(data);
|
|
||||||
displayContacts(filteredContacts);
|
document.getElementById('loading').classList.add('hidden');
|
||||||
} catch (error) {
|
document.getElementById('contactsList').classList.remove('hidden');
|
||||||
document.getElementById('loading').classList.add('hidden');
|
|
||||||
document.getElementById('error').classList.remove('hidden');
|
updateStats(data);
|
||||||
document.getElementById('error').innerHTML = '<p>Chyba při načítání kontaktů: ' + error.message + '</p>';
|
displayContacts(filteredContacts);
|
||||||
}
|
} catch (error) {
|
||||||
}
|
document.getElementById('loading').classList.add('hidden');
|
||||||
|
document.getElementById('error').classList.remove('hidden');
|
||||||
function updateStats(data) {
|
document.getElementById('error').innerHTML = '<p>Chyba při načítání kontaktů: ' + error.message + '</p>';
|
||||||
const lastUpdated = new Date(data.last_updated).toLocaleString('cs-CZ');
|
}
|
||||||
const table1Count = allContacts.filter(c => c.table === 1).length;
|
}
|
||||||
const table2Count = allContacts.filter(c => c.table === 2).length;
|
|
||||||
|
function updateStats(data) {
|
||||||
document.getElementById('stats').innerHTML =
|
const lastUpdated = new Date(data.last_updated).toLocaleString('cs-CZ');
|
||||||
'Celkem: ' + allContacts.length + ' kontaktů ' +
|
const table1Count = allContacts.filter(c => c.table === 1).length;
|
||||||
'(Tabulka 1: ' + table1Count + ', Tabulka 2: ' + table2Count + ') | ' +
|
const table2Count = allContacts.filter(c => c.table === 2).length;
|
||||||
'Aktualizováno: ' + lastUpdated;
|
|
||||||
}
|
document.getElementById('stats').innerHTML =
|
||||||
|
'Celkem: ' + allContacts.length + ' kontaktů ' +
|
||||||
function displayContacts(contacts) {
|
'(Tabulka 1: ' + table1Count + ', Tabulka 2: ' + table2Count + ') | ' +
|
||||||
const container = document.getElementById('contacts');
|
'Aktualizováno: ' + lastUpdated;
|
||||||
container.innerHTML = '';
|
}
|
||||||
|
|
||||||
if (contacts.length === 0) {
|
function displayContacts(contacts) {
|
||||||
container.innerHTML = '<div class="col-span-full text-center py-8 text-gray-500">Žádné kontakty nenalezeny</div>';
|
const container = document.getElementById('contacts');
|
||||||
return;
|
container.innerHTML = '';
|
||||||
}
|
|
||||||
|
if (contacts.length === 0) {
|
||||||
contacts.forEach(contact => {
|
container.innerHTML = '<div class="col-span-full text-center py-8 text-gray-500">Žádné kontakty nenalezeny</div>';
|
||||||
const contactCard = document.createElement('div');
|
return;
|
||||||
contactCard.className = 'bg-gray-50 p-4 rounded-lg border border-gray-200 hover:shadow-md transition-shadow';
|
}
|
||||||
|
|
||||||
contactCard.innerHTML =
|
contacts.forEach(contact => {
|
||||||
'<div class="flex items-start justify-between mb-2">' +
|
const contactCard = document.createElement('div');
|
||||||
'<h3 class="font-semibold text-gray-800 text-lg">' + (contact.name || 'Bez jména') + '</h3>' +
|
contactCard.className = 'bg-gray-50 p-4 rounded-lg border border-gray-200 hover:shadow-md transition-shadow';
|
||||||
'<span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">T' + contact.table + '</span>' +
|
|
||||||
'</div>' +
|
contactCard.innerHTML =
|
||||||
(contact.position ? '<p class="text-gray-600 mb-3">' + contact.position + '</p>' : '') +
|
'<div class="flex items-start justify-between mb-2">' +
|
||||||
'<div class="space-y-1">' +
|
'<h3 class="font-semibold text-gray-800 text-lg">' + (contact.name || 'Bez jména') + '</h3>' +
|
||||||
(contact.phone ? '<div class="flex items-center text-sm"><span class="font-medium text-gray-700 w-16">Tel:</span><a href="tel:' + contact.phone + '" class="text-blue-600 hover:underline">' + contact.phone + '</a></div>' : '') +
|
'<span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">T' + contact.table + '</span>' +
|
||||||
(contact.service_phone ? '<div class="flex items-center text-sm"><span class="font-medium text-gray-700 w-16">Služ:</span><a href="tel:' + contact.service_phone + '" class="text-blue-600 hover:underline">' + contact.service_phone + '</a></div>' : '') +
|
'</div>' +
|
||||||
'</div>';
|
(contact.position ? '<p class="text-gray-600 mb-3">' + contact.position + '</p>' : '') +
|
||||||
|
'<div class="space-y-1">' +
|
||||||
container.appendChild(contactCard);
|
(contact.phone ? '<div class="flex items-center text-sm"><span class="font-medium text-gray-700 w-16">Tel:</span><a href="tel:' + contact.phone + '" class="text-blue-600 hover:underline">' + contact.phone + '</a></div>' : '') +
|
||||||
});
|
(contact.service_phone ? '<div class="flex items-center text-sm"><span class="font-medium text-gray-700 w-16">Služ:</span><a href="tel:' + contact.service_phone + '" class="text-blue-600 hover:underline">' + contact.service_phone + '</a></div>' : '') +
|
||||||
}
|
'</div>';
|
||||||
|
|
||||||
function filterContacts() {
|
container.appendChild(contactCard);
|
||||||
const query = document.getElementById('searchInput').value.toLowerCase();
|
});
|
||||||
filteredContacts = allContacts.filter(contact =>
|
}
|
||||||
(contact.name && contact.name.toLowerCase().includes(query)) ||
|
|
||||||
(contact.position && contact.position.toLowerCase().includes(query)) ||
|
function filterContacts() {
|
||||||
(contact.phone && contact.phone.includes(query)) ||
|
const query = document.getElementById('searchInput').value.toLowerCase();
|
||||||
(contact.service_phone && contact.service_phone.includes(query))
|
filteredContacts = allContacts.filter(contact =>
|
||||||
);
|
(contact.name && contact.name.toLowerCase().includes(query)) ||
|
||||||
displayContacts(filteredContacts);
|
(contact.position && contact.position.toLowerCase().includes(query)) ||
|
||||||
}
|
(contact.phone && contact.phone.includes(query)) ||
|
||||||
|
(contact.service_phone && contact.service_phone.includes(query))
|
||||||
async function reloadContacts() {
|
);
|
||||||
const btn = document.getElementById('reloadBtn');
|
displayContacts(filteredContacts);
|
||||||
btn.disabled = true;
|
}
|
||||||
btn.textContent = 'Načítání...';
|
|
||||||
|
async function reloadContacts() {
|
||||||
try {
|
const btn = document.getElementById('reloadBtn');
|
||||||
await fetch('/reload', { method: 'POST' });
|
btn.disabled = true;
|
||||||
await loadContacts();
|
btn.textContent = 'Načítání...';
|
||||||
} catch (error) {
|
|
||||||
alert('Chyba při obnovování: ' + error.message);
|
try {
|
||||||
} finally {
|
await fetch('/reload', { method: 'POST' });
|
||||||
btn.disabled = false;
|
await loadContacts();
|
||||||
btn.textContent = 'Obnovit';
|
} catch (error) {
|
||||||
}
|
alert('Chyba při obnovování: ' + error.message);
|
||||||
}
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
// Load contacts on page load
|
btn.textContent = 'Obnovit';
|
||||||
loadContacts();
|
}
|
||||||
</script>
|
}
|
||||||
</body>
|
|
||||||
</html>`
|
// Load contacts on page load
|
||||||
}
|
loadContacts();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>`
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user