码桶

发现社区成员的开源项目

data.js8.5 KB
/**
 * data.js - 域名數據管理層 (localStorage)
 * 前後台共享的數據存取接口
 */

const DomainDB = {
  STORAGE_KEY: 'domain_market_data',
  ADMIN_PASSWORD_KEY: 'domain_market_admin_pwd',
  DEFAULT_PASSWORD: 'admin888',

  // 獲取所有域名
  getAll() {
    const raw = localStorage.getItem(this.STORAGE_KEY);
    if (!raw) {
      // 首次使用,載入範例數據
      const sample = this.getSampleData();
      this.save(sample);
      return sample;
    }
    try {
      return JSON.parse(raw);
    } catch (e) {
      console.error('數據解析失敗', e);
      return [];
    }
  },

  // 保存所有域名(同步到 localStorage + KV)
  save(domains) {
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(domains));
    if (typeof DataSync !== 'undefined') DataSync.save('domains', domains);
  },

  // 新增域名
  add(domain) {
    const all = this.getAll();
    domain.id = Date.now();
    domain.status = domain.status || 'available'; // available / sold / pending
    domain.createdAt = new Date().toISOString();
    all.push(domain);
    this.save(all);
    return domain;
  },

  // 更新域名
  update(id, data) {
    const all = this.getAll();
    const idx = all.findIndex(d => d.id === id);
    if (idx >= 0) {
      all[idx] = { ...all[idx], ...data };
      this.save(all);
      return all[idx];
    }
    return null;
  },

  // 刪除域名
  delete(id) {
    const all = this.getAll();
    const filtered = all.filter(d => d.id !== id);
    this.save(filtered);
    return filtered.length < all.length;
  },

  // 查詢(可按分類、關鍵詞、狀態篩選)
  query(filters = {}) {
    let all = this.getAll();

    // 預設只顯示 available 和 pending
    if (!filters.includeAll) {
      all = all.filter(d => d.status !== 'sold');
    }

    if (filters.category && filters.category !== 'all') {
      all = all.filter(d => d.category === filters.category);
    }

    if (filters.keyword) {
      const kw = filters.keyword.toLowerCase();
      all = all.filter(d =>
        d.name.toLowerCase().includes(kw) ||
        (d.description && d.description.toLowerCase().includes(kw))
      );
    }

    if (filters.status && filters.status !== 'all') {
      all = all.filter(d => d.status === filters.status);
    }

    // 按分類排序,再按價格排序
    all.sort((a, b) => {
      if (a.category !== b.category) {
        return a.category.localeCompare(b.category, 'zh-Hant');
      }
      return (a.price || 0) - (b.price || 0);
    });

    return all;
  },

  // 獲取所有分類
  getCategories() {
    const all = this.getAll();
    const cats = [...new Set(all.map(d => d.category))];
    return cats.sort((a, b) => a.localeCompare(b, 'zh-Hant'));
  },

  // 獲取統計
  getStats() {
    const all = this.getAll();
    return {
      total: all.length,
      available: all.filter(d => d.status === 'available').length,
      sold: all.filter(d => d.status === 'sold').length,
      pending: all.filter(d => d.status === 'pending').length,
      totalValue: all.filter(d => d.status !== 'sold').reduce((sum, d) => sum + (d.price || 0), 0)
    };
  },

  // 導出 JSON
  export() {
    return JSON.stringify(this.getAll(), null, 2);
  },

  // 導入 JSON
  import(jsonStr, mode = 'merge') {
    let data;
    try {
      data = JSON.parse(jsonStr);
    } catch (e) {
      return { success: false, error: 'JSON 格式錯誤' };
    }

    if (!Array.isArray(data)) {
      return { success: false, error: '數據格式不正確,需要陣列' };
    }

    if (mode === 'replace') {
      this.save(data);
    } else {
      const existing = this.getAll();
      data.forEach(d => {
        if (!d.id) d.id = Date.now() + Math.random();
        existing.push(d);
      });
      this.save(existing);
    }

    return { success: true, count: data.length };
  },

  // 清空所有數據
  clearAll() {
    localStorage.removeItem(this.STORAGE_KEY);
    if (typeof DataSync !== 'undefined') DataSync.save('domains', []);
  },

  // 密碼管理
  getPassword() {
    return localStorage.getItem(this.ADMIN_PASSWORD_KEY) || this.DEFAULT_PASSWORD;
  },

  setPassword(newPwd) {
    localStorage.setItem(this.ADMIN_PASSWORD_KEY, newPwd);
  },

  verifyPassword(pwd) {
    return pwd === this.getPassword();
  },

  // 範例數據
  getSampleData() {
    return [
      { id: 1001, category: '數字類', name: '6666.HK', price: 15000, currency: 'HKD', contact: '[email protected]', status: 'available', createdAt: '2024-01-01T00:00:00Z' },
      { id: 1002, category: '數字類', name: '8888.HK', price: 20000, currency: 'HKD', contact: '[email protected]', status: 'available', createdAt: '2024-01-01T00:00:00Z' },
      { id: 1003, category: '商務類', name: 'www.ticket.hk', price: 10000, currency: 'HKD', contact: '[email protected]', status: 'available', createdAt: '2024-01-01T00:00:00Z' },
      { id: 1004, category: '商務類', name: 'www.ticket.com.hk', price: 10000, currency: 'HKD', contact: '[email protected]', status: 'available', createdAt: '2024-01-01T00:00:00Z' },
      { id: 1005, category: '商務類', name: 'www.hotel.hk', price: 20000, currency: 'HKD', contact: '[email protected]', status: 'available', createdAt: '2024-01-01T00:00:00Z' },
      { id: 1006, category: '商務類', name: 'www.shop.hk', price: 12000, currency: 'HKD', contact: '[email protected]', status: 'available', createdAt: '2024-01-01T00:00:00Z' },
      { id: 1007, category: '科技類', name: 'ai.hk', price: 50000, currency: 'HKD', contact: '[email protected]', status: 'available', createdAt: '2024-01-01T00:00:00Z' },
      { id: 1008, category: '科技類', name: 'cloud.hk', price: 30000, currency: 'HKD', contact: '[email protected]', status: 'available', createdAt: '2024-01-01T00:00:00Z' },
      { id: 1009, category: '金融類', name: 'invest.hk', price: 25000, currency: 'HKD', contact: '[email protected]', status: 'available', createdAt: '2024-01-01T00:00:00Z' },
      { id: 1010, category: '金融類', name: 'bank.hk', price: 40000, currency: 'HKD', contact: '[email protected]', status: 'pending', createdAt: '2024-01-01T00:00:00Z' },
    ];
  }
};

/**
 * SiteConfig - 網站設置管理(聯絡資訊、標題文案等)
 * 後台可修改,前台自動讀取
 */
const SiteConfig = {
  STORAGE_KEY: 'domain_market_site_config',

  getDefaults() {
    return {
      // 標題區
      titleEn: 'These Great Domain Names for Sale!',
      titleZh: '此 域 名 售 讓 !',
      introText: '一個優異的名字是帶來無限商機的首要元素,我們現正推出大量優異域名供閣下選擇,為你的生意做好準備,打開互聯網市場的業務,交易安全可靠,值得信賴。',
      // 特點列表
      feature1Title: '簡單易記',
      feature1Desc: '簡單易記的域名方便客人記住,提升顧客瀏覽意慾',
      feature2Title: '主題直接',
      feature2Desc: '部分域名主題直接,掌握行業網絡領先地位',
      feature3Title: '交易安全',
      feature3Desc: '交易流程安全透明,資料保密,放心信賴',
      // 聯絡資訊
      contactPerson: 'Edmond Ng',
      contactPerson2: 'Leon Li',
      contactPhone: '244 66666',
      whatsappNumber: '85265166666',
      email1: '[email protected]',
      email2: '[email protected]',
      currency: 'HKD',
      // 聯絡頁面
      contactTitleEn: 'Contact Us',
      contactTitleZh: '聯 絡 我 們',
      contactIntro: '如欲購買域名或有任何查詢,歡迎與我們聯絡,我們將盡快覆你!',
      // 額外聯絡方式(可選)
      wechatId: '',
      telegramId: '',
      address: '',
      businessHours: ''
    };
  },

  get() {
    const raw = localStorage.getItem(this.STORAGE_KEY);
    if (!raw) {
      const defaults = this.getDefaults();
      this.save(defaults);
      return defaults;
    }
    try {
      const saved = JSON.parse(raw);
      // 合併預設值,確保新增欄位不會缺失
      return { ...this.getDefaults(), ...saved };
    } catch (e) {
      return this.getDefaults();
    }
  },

  save(config) {
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(config));
    if (typeof DataSync !== 'undefined') DataSync.save('config', config);
  },

  update(partial) {
    const current = this.get();
    const updated = { ...current, ...partial };
    this.save(updated);
    return updated;
  },

  reset() {
    const defaults = this.getDefaults();
    this.save(defaults);
    return defaults;
  }
};