メインコンテンツへスキップ
見出し画像

GASで「アポ調整Webアプリ」コード配布有

    もう有料ツールはいらない。「アポ調整Webアプリ」はGoogleだけで作れる。GASで作る便利グッズ。

    わからないことあればコメントいただければサポートします!
    5分あればセッティングできます。

    https://youtu.be/N-Svnuyb-pY

    外回りの営業や個人事業主の皆さん、こんなメールを送る前の、あの「無」の時間、ありませんか?

    「〇〇様、お打ち合わせの件、以下の日程でご都合いかがでしょうか?」

    この一文に続く、候補日時を打ち込む、あの時間。

    まず、スマホやPCのカレンダーと睨めっこ。
    (A社からB社への移動は1時間…ってことは、午後は14時からなら大丈夫だな)
    (来週の水曜は終日空いているけど、提案資料の準備に集中したいから避けたい…)
    (よし、候補は3つに絞れたぞ!)

    ・10月26日(木) 14:00〜15:00
    ・10月27日(金) 11:00〜12:00
    ・10月30日(月) 16:00〜17:00

    この**「自分のカレンダーから候補を探し出し、手入力でリストアップする」**という、単純だけど地味に面倒な作業。もしお客様の都合が悪ければ、またカレンダーとにらめっこして、この作業をやり直すことになります。

    この繰り返しに「もう、うんざりだ!」と感じているのは、きっと私だけではないはずです。

    でも、安心してください。無料でいつも使っているGoogleのツールだけで、この悩みを解決する「あなた専用のWebアプリ」が作れてしまうんです。Google Apps Script (GAS) です。

    今回の主役は「GAS」。

    「アプリ開発」と聞くと、なんだか難しそうですよね。でもGASは違います。

    GASは、一言でいえばGmailやカレンダー、スプレッドシートなど、あなたが普段使っているツールたちを連携できます。

    そして、GASの数ある機能の中でも特にパワフルなのが、「ウェブアプリとして公開する機能」。
    これを使うと、ただの自動化ツールではなく、**自分だけのオリジナルWebサイト(アプリ)**をインターネット上に公開できるんです。

    僕だけのシンプル「アポ調整Webアプリ」

    今回創ったのは、店舗用の大がかりなものではなく、あくまで個人が使うための、シンプルで研ぎ澄まされたアポイント調整ツールです。

    【STEP 1: あなたが候補を選ぶ管理画面】
    まず、あなた専用の管理ページ(Webアプリ)を開きます。ここには、あなたのGoogleカレンダーから「アポ可能な時間」だけが自動でリストアップされています。お客様に提示したい時間をいくつか選び、「URLを生成」ボタンをクリック。


    画像


    画像


    【STEP 2: お客様が希望順を選ぶ画面】

    生成されたURLをお客様に送ると、専用のページ(これもWebアプリ)が表示されます。お客様は提示された候補の中から、希望の日時を順番に選んで送信します。


    画像

    【STEP 3: 通知メール&ワンクリック登録】
    お客様が送信すると、あなたのGmailに通知が届きます。メールには希望順位が明記されており、各日時の横にある「この日時でカレンダーに登録」ボタンを押すだけ。これでアポ確定&カレンダーへの登録が完了です。


    画像

    この一連の流れ、すべてGASという一つの技術だけで完結しているのがポイントです。

    さあ、創ってみよう!GASでWebアプリを作る3ステップ

    「面白そうだけど、やっぱり難しそう…」
    大丈夫です。大まかな流れはたったの3ステップ。そして、一番難しい**「設計とコーディング」は、AIにアシスタントをお願い**すればOKです。

    Step 1. GASプロジェクトを用意する

    1. PCでGoogle Driveを開き、「新規」ボタンをクリック。

    2. 「その他」から「Google Apps Script」を選択します。(見当たらなければ「アプリを追加」から探してみてください)

    3. すると、見慣れないコード編集画面が開きます。これがあなたの開発基地です!

    Step 2. コードを用意する(設計はAIアシスタントにお任せ!)

    ここでAIの出番です。プログラミングを全部自分で書く必要はありません。AIに「こんなWebアプリが欲しい!」と伝えるだけで、設計図(コード)を書いてくれます。

    【AIへの依頼文(例)】
    Google Apps Scriptで、ウェブアプリ機能を使ってアポイント調整ツールを作りたいです。サーバーサイドのdoGet関数と、フロントエンドのHTML/CSS/JavaScriptコードをください。…(以下、やりたいことを具体的に)

    AIが生成したコードを、GASの編集画面にコピペします。

    • doGetなどの命令が書かれたコード → コード.gs ファイルに。

    • ページの見た目(HTML)のコード → 「ファイル」>「新規」>「HTMLファイル」で新しいファイルを作り、そこに貼り付けます。

    Step 3. 「ウェブアプリ」として世界に公開!

    コードが準備できたら、いよいよ公開(デプロイ)です。ここがGASの真骨頂!

    1. 画面右上の青い「デプロイ」ボタンをクリックし、「新しいデプロイ」を選択。

    2. 歯車マークの「種類の選択」で**「ウェブアプリ」**を選びます。

    3. ここが重要! 「アクセスできるユーザー」を**「全員」**に設定します。こうしないと、お客様がページを見ることができません。

    4. 「デプロイ」ボタンを押すと、承認を求められた後、あなただけのWebアプリのURLが発行されます!

    このURLが、あなたの新しい相棒の入り口です。

    コメントいただければサポートします!

    5分あればセッティングできます。

    ご自身でセッティングされる場合は以下のコードをお使いください。


    【配布用コード】アポイント調整Webアプリ

    このツールは3つのファイルで構成されています。
    以下のコードを、あなたのGoogle Apps Scriptプロジェクトの対応するファイルにそれぞれコピー&ペーストしてください。

    1. `コード.gs` (サーバー側の処理)

    2. `admin.html` (管理者用の画面)

    3. `customer.html` (お客様用の画面)


    1. `コード.gs`

    GASエディタで最初から開かれている `コード.gs` の内容をすべて消し、以下のコードを貼り付けてください。

    // --- 設定項目 ---
    const CALENDAR_ID = 'primary'; // 対象のカレンダーID 'primary'はメインカレンダー
    const BUFFER_HOURS = 1; // 予定の前後にとる余裕時間(単位:時間)
    const SLOT_DURATION_MINUTES = 60; // 打ち合わせの時間(単位:分)
    const SEARCH_DAYS = 14; // 何日先まで空き時間を探すか
    const BUSINESS_START_HOUR = 9; // 営業開始時間(9時)
    const BUSINESS_END_HOUR = 18; // 営業終了時間(18時)
    const BITLY_ACCESS_TOKEN = ''; // ★★★ Bitlyで取得したアクセストークンを設定 ★★★
    // ----------------------------------------------------------------------------------------------------
    
    /**
     * Webアプリにアクセスがあった時のメイン処理
     */
    function doGet(e) {
      // URLに ?slots=... パラメータがある場合はお客様向けページを表示
      if (e.parameter.slots) {
        const slotsParam = e.parameter.slots;
        const slotStrings = slotsParam.split(',');
        const finalSlots = slotStrings.map(s => new Date(s));
        const template = HtmlService.createTemplateFromFile('customer');
        template.finalSlots = finalSlots;
        return template.evaluate().setTitle('ご希望日時の選択');
      } 
      // パラメータがない場合は管理者向けページを表示
      else {
        const allSlots = getAvailableSlots();
        const template = HtmlService.createTemplateFromFile('admin');
        template.allSlots = allSlots;
        return template.evaluate().setTitle('管理者用 - 日程候補の選択');
      }
    }
    
    /**
     * お客様が予約リクエストを送信した時に実行される関数 (希望順位対応版)
     * @param {object} bookingData - お客様が入力したデータ({name: "...", choices: ["...", "..."]})
     */
    function processBooking(bookingData) {
      try {
        const customerName = bookingData.name;
        // bookingData.choices は、お客様が選択した順番の配列
        const selectedChoices = bookingData.choices.map(t => new Date(t));
    
        if (!customerName || customerName.trim() === "") {
          throw new Error('お名前が入力されていません。');
        }
        if (!selectedChoices || selectedChoices.length === 0) {
          throw new Error('ご希望日時が選択されていません。');
        }
    
        const myEmail = Session.getActiveUser().getEmail();
        const subject = `【日程調整】${customerName}様から新しい予約リクエスト(希望順位付き)`;
        
        let timeProposalsHtml = '';
        let timeProposalsText = '';
    
        // お客様が選んだ順番 (selectedChoices 配列の順) でメール本文を生成
        selectedChoices.forEach((selectedTime, index) => {
          const endTime = new Date(selectedTime.getTime() + SLOT_DURATION_MINUTES * 60 * 1000);
          const formatForCalendar = (date) => date.toISOString().replace(/-|:|\.\d+/g, '');
          const calendarDates = `${formatForCalendar(selectedTime)}/${formatForCalendar(endTime)}`;
          const eventTitle = `${customerName}様との打ち合わせ`;
          const eventDetails = `お客様からの予約リクエストです。\n希望順位: 第${index + 1}希望\n日時: ${selectedTime.toLocaleString('ja-JP', { timeZone: 'Asia/Tokyo' })}\n所要時間: ${SLOT_DURATION_MINUTES}分`;
          const calendarUrl = `https://www.google.com/calendar/render?action=TEMPLATE&text=${encodeURIComponent(eventTitle)}&dates=${calendarDates}&details=${encodeURIComponent(eventDetails)}`;
          const formattedTime = selectedTime.toLocaleString('ja-JP', { timeZone: 'Asia/Tokyo', year: 'numeric', month: 'long', day: 'numeric', weekday: 'short', hour: '2-digit', minute: '2-digit' });
    
          timeProposalsHtml += `
            <tr>
              <td style="padding: 12px; border: 1px solid #ddd; font-weight: bold;">第${index + 1}希望</td>
              <td style="padding: 12px; border: 1px solid #ddd;">${formattedTime}</td>
              <td style="padding: 12px; border: 1px solid #ddd; text-align: center;">
                <a href="${calendarUrl}" target="_blank" style="display: inline-block; padding: 8px 16px; font-size: 14px; color: white; background-color: #4285F4; text-decoration: none; border-radius: 5px;">この日時で登録</a>
              </td>
            </tr>
          `;
          timeProposalsText += `第${index + 1}希望: ${formattedTime}\nカレンダー登録URL: ${calendarUrl}\n\n`;
        });
    
        const htmlBody = `
          <p style="font-size:16px;">${customerName}様から以下の希望順位で予約リクエストがありました。</p>
          <p>ご希望の日時を選択し、Googleカレンダーに予定を登録してください。</p>
          <table style="border-collapse: collapse; margin: 20px 0; width: 100%;">
            <thead>
              <tr>
                <th style="padding: 12px; border: 1px solid #ddd; background-color: #f2f2f2;">希望順位</th>
                <th style="padding: 12px; border: 1px solid #ddd; background-color: #f2f2f2;">希望日時</th>
                <th style="padding: 12px; border: 1px solid #ddd; background-color: #f2f2f2;">アクション</th>
              </tr>
            </thead>
            <tbody>
              ${timeProposalsHtml}
            </tbody>
          </table>
          <p style="font-size:12px; color:#777; margin-top:20px;">※いずれかの「この日時で登録」ボタンを押して予定を登録すると、その時間枠は自動的に他の人から予約できなくなります。</p>
        `;
    
        const body = `${customerName}様から予約リクエストがありました。\n\n以下の希望日時(希望順)から選択し、リンクをクリックしてカレンダーに予定を登録してください:\n\n${timeProposalsText}`;
    
        MailApp.sendEmail({ to: myEmail, subject: subject, body: body, htmlBody: htmlBody });
    
        return { status: 'success' };
    
      } catch (e) {
        console.error('予約処理中にエラーが発生しました: ' + e.toString());
        throw new Error('サーバー側でエラーが発生しました。' + e.message);
      }
    }
    
    /**
     * Googleカレンダーから全ての空き時間を取得する関数
     */
    function getAvailableSlots() {
      const now = new Date();
      const searchStartDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), BUSINESS_START_HOUR);
      const searchEndDate = new Date(now.getTime() + SEARCH_DAYS * 24 * 60 * 60 * 1000);
      
      const calendar = CalendarApp.getCalendarById(CALENDAR_ID);
      const events = calendar.getEvents(searchStartDate, searchEndDate);
      
      const busyTimes = events.map(event => {
        const start = new Date(event.getStartTime().getTime() - BUFFER_HOURS * 60 * 60 * 1000);
        const end = new Date(event.getEndTime().getTime() + BUFFER_HOURS * 60 * 60 * 1000);
        return { start: start, end: end };
      });
    
      const availableSlots = [];
      let currentTime = new Date(searchStartDate.getTime());
      
      while (currentTime < searchEndDate) {
        const day = currentTime.getDay();
        const hour = currentTime.getHours();
        
        // 営業日・営業時間内かをチェック
        if (day >= 0 && day <= 6 && hour >= BUSINESS_START_HOUR && hour < BUSINESS_END_HOUR) {
          const slotStart = new Date(currentTime.getTime());
          const slotEnd = new Date(slotStart.getTime() + SLOT_DURATION_MINUTES * 60 * 1000);
          let isAvailable = true;
          for (const busy of busyTimes) {
            if (slotStart < busy.end && slotEnd > busy.start) {
              isAvailable = false;
              break;
            }
          }
          if (isAvailable && slotStart > now) { // 過去の時間は候補にしない
            availableSlots.push(slotStart);
          }
        }
        currentTime.setTime(currentTime.getTime() + SLOT_DURATION_MINUTES * 60 * 1000);
      }
      return availableSlots;
    }
    
    /**
     * Bitly APIを使ってURLを短縮する関数
     * @param {string} longUrl - 長い元のURL
     * @return {string} 短縮されたURL。失敗した場合は元の長いURLを返す。
     */
    function generateBitlyShortUrl(longUrl) {
      // アクセストークンが設定されていない場合は、短縮せずに元のURLを返す
      if (BITLY_ACCESS_TOKEN === '') {
        console.log('Bitlyアクセストークンが設定されていないため、URL短縮をスキップします。');
        return longUrl;
      }
    
      const apiUrl = 'https://api-ssl.bitly.com/v4/shorten';
      
      const payload = {
        "long_url": longUrl
      };
    
      const options = {
        'method': 'post',
        'contentType': 'application/json',
        'headers': {
          'Authorization': 'Bearer ' + BITLY_ACCESS_TOKEN
        },
        'payload': JSON.stringify(payload),
        'muteHttpExceptions': true // APIからのエラーを例外として扱わない
      };
    
      try {
        const response = UrlFetchApp.fetch(apiUrl, options);
        const result = JSON.parse(response.getContentText());
        
        // Bitlyからのレスポンスが成功(200 or 201)か確認
        if (response.getResponseCode() === 200 || response.getResponseCode() === 201) {
          return result.link; // 成功:短縮されたURL (e.g., "bit.ly/xxxx")
        } else {
          // 失敗:エラー内容をログに出力し、元のURLを返す
          console.error('Bitly APIエラー: ' + result.description);
          return longUrl;
        }
      } catch (e) {
        // GAS自体のエラー:ログに出力し、元のURLを返す
        console.error('URLの短縮処理中にエラーが発生しました: ' + e.toString());
        return longUrl;
      }
    }

    2. `admin.html`

    GASエディタの左側にある「ファイル」の「+」アイコンをクリックし、「HTML」を選択します。ファイル名を `admin` と入力して、新しいHTMLファイルを作成してください。
    作成したファイルの中身をすべて消し、以下のコードを貼り付けます。

    <!DOCTYPE html>
    <html>
    <head>
        <base target="_top">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>管理者用 - 日程候補の選択</title>
        <style>
            body { font-family: sans-serif; padding: 20px; max-width: 800px; margin: auto; }
            .step { border: 1px solid #ccc; padding: 20px; margin-bottom: 20px; border-radius: 8px; }
            h2 { color: #005a9c; }
            
            .weekday-selector { 
                display: flex; 
                flex-wrap: wrap; 
                align-items: center; /* 縦位置を揃える */
                gap: 15px; 
                margin-bottom: 20px; 
                padding: 10px; 
                background: #f7f7f7; 
                border-radius: 5px; 
            }
            .weekday-selector label { 
                cursor: pointer; 
                user-select: none;
            }
            .deselect-all {
                margin-left: auto; /* 右端に寄せる */
                padding: 5px 10px;
                background-color: #dc3545;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
            }
            
            .slot-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 10px; }
            .slot-item label { display: block; padding: 10px; border: 1px solid #ddd; border-radius: 5px; cursor: pointer; transition: background-color 0.2s; }
            .slot-item input:checked + label { background-color: #e0f7fa; border-color: #007bff; }
            #url-result { margin-top: 20px; padding: 15px; background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 5px; display: none; }
            #final-url { width: 100%; padding: 5px; box-sizing: border-box; }
            button { padding: 10px 20px; font-size: 16px; cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 5px; }
        </style>
    </head>
    <body>
        <h1>日程調整 管理ページ</h1>
    
        <div class="step">
            <h2>Step 1 & 2: お客様に提示する候補を選択</h2>
            <p>提示したい日時にチェックを入れてください。</p>
            
            <div class="weekday-selector">
                <strong>曜日で一括選択/解除:</strong>
                <label><input type="checkbox" onchange="toggleWeekday(1, this.checked)"> 月</label>
                <label><input type="checkbox" onchange="toggleWeekday(2, this.checked)"> 火</label>
                <label><input type="checkbox" onchange="toggleWeekday(3, this.checked)"> 水</label>
                <label><input type="checkbox" onchange="toggleWeekday(4, this.checked)"> 木</label>
                <label><input type="checkbox" onchange="toggleWeekday(5, this.checked)"> 金</label>
                <label><input type="checkbox" onchange="toggleWeekday(0, this.checked)"> 日</label>
                <label><input type="checkbox" onchange="toggleWeekday(6, this.checked)"> 土</label>
                <button type="button" class="deselect-all" onclick="deselectAll()">全部解除</button>
            </div>
    
            <form id="candidate-form">
                <div class="slot-list">
                    <? if (allSlots.length > 0) { ?>
                        <? for (var i = 0; i < allSlots.length; i++) { ?>
                            <div class="slot-item" data-weekday="<?= allSlots[i].getDay() ?>">
                                <input type="checkbox" name="selected_slots" value="<?= allSlots[i].toISOString() ?>" id="slot<?= i ?>" checked>
                                <label for="slot<?= i ?>">
                                    <?= allSlots[i].toLocaleString('ja-JP', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'short', hour: '2-digit', minute: '2-digit' }) ?>
                                </label>
                            </div>
                        <? } ?>
                    <? } else { ?> <p>現在、利用可能な空き時間がありません。</p> <? } ?>
                </div>
                <br>
                <button type="submit">Step 3: お客様向けのURLを生成する</button>
            </form>
        </div>
    
        <div id="url-result">
            <h3>お客様にこのURLを共有してください</h3>
            <input type="text" id="final-url" readonly>
            <button onclick="copyUrl()">URLをコピー</button>
        </div>
    
    <script>
        document.getElementById('candidate-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const submitButton = this.querySelector('button[type="submit"]');
            submitButton.disabled = true;
            submitButton.textContent = 'URLを生成中...';
    
            const formData = new FormData(this);
            const selectedSlots = formData.getAll('selected_slots');
            
            if (selectedSlots.length === 0) {
                alert('提示する候補を1つ以上選択してください。');
                submitButton.disabled = false;
                submitButton.textContent = 'Step 3: お客様向けのURLを生成する';
                return;
            }
    
            const slotsParam = selectedSlots.join(',');
            const baseUrl = "<?= ScriptApp.getService().getUrl() ?>";
            const longUrl = baseUrl + "?slots=" + encodeURIComponent(slotsParam);
            
            google.script.run
                .withSuccessHandler(onUrlGenerated)
                .withFailureHandler(onUrlGenerationFailure)
                .generateBitlyShortUrl(longUrl);
        });
    
        function onUrlGenerated(url) {
            const submitButton = document.querySelector('#candidate-form button[type="submit"]');
            submitButton.disabled = false;
            submitButton.textContent = 'Step 3: お客様向けのURLを生成する';
            
            document.getElementById('url-result').style.display = 'block';
            document.getElementById('final-url').value = url;
        }
    
        function onUrlGenerationFailure(error) {
            const submitButton = document.querySelector('#candidate-form button[type="submit"]');
            submitButton.disabled = false;
            submitButton.textContent = 'Step 3: お客様向けのURLを生成する';
    
            alert('URLの生成中にエラーが発生しました: ' + error.message);
        }
    
        function copyUrl() {
            const urlInput = document.getElementById('final-url');
            urlInput.select();
            document.execCommand('copy');
            alert('URLをクリップボードにコピーしました!');
        }
        function toggleWeekday(weekday, isChecked) {
            const allSlotItems = document.querySelectorAll(`.slot-item[data-weekday="${weekday}"]`);
            allSlotItems.forEach(item => {
                const checkbox = item.querySelector('input[type="checkbox"]');
                if (checkbox) checkbox.checked = isChecked;
            });
        }
        function deselectAll() {
            const allCheckboxes = document.querySelectorAll('.slot-list input[type="checkbox"]');
            allCheckboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            const weekdayCheckboxes = document.querySelectorAll('.weekday-selector input[type="checkbox"]');
            weekdayCheckboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
        }
    </script>
    </body>
    </html>

    3. `customer.html`

    再び「ファイル」の「+」アイコンから「HTML」を選択し、今度は `customer` という名前でファイルを作成します。
    作成したファイルの中身をすべて消し、以下のコードを貼り付けてください。

    <!DOCTYPE html>
    <html>
    <head>
        <base target="_top">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>ご希望日時の選択</title>
        <style>
            body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding: 20px; display: flex; justify-content: center; align-items: flex-start; min-height: 100vh; }
            .container { background-color: #ffffff; padding: 30px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); max-width: 600px; width: 100%; box-sizing: border-box; }
            h1, h2 { color: #005a9c; text-align: center; margin-top: 0; }
            h2 { font-size: 1.2em; border-bottom: 2px solid #eef; padding-bottom: 10px; margin-bottom: 15px;}
            p { text-align: center; line-height: 1.6; }
            .form-group { margin-bottom: 20px; }
            .form-group label { font-weight: bold; display: block; margin-bottom: 5px; }
            .form-group input[type="text"] { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
            button { font-size: 16px; cursor: pointer; border-radius: 5px; padding: 10px 20px; border: none; }
            button.submit-btn { width: 100%; font-weight: bold; color: #ffffff; background-color: #28a745; margin-top: 25px; transition: background-color 0.2s ease; }
            button.submit-btn:hover { background-color: #218838; }
            button.submit-btn:disabled { background-color: #aaa; cursor: not-allowed; }
            
            #selected-choices-area { margin-bottom: 30px; }
            .choice-slot { display: flex; align-items: center; justify-content: space-between; padding: 12px; border: 1px dashed #ccc; border-radius: 8px; margin-bottom: 10px; }
            .choice-slot .placeholder { color: #888; }
            .choice-slot .actions button { background-color: #dc3545; color: white; padding: 5px 10px; font-size: 12px; }
            
            #slot-list-area { max-height: 40vh; overflow-y: auto; padding-right: 10px; border-top: 1px solid #eee; border-bottom: 1px solid #eee; padding-top: 15px; padding-bottom: 15px; }
            .slot-item { display: flex; align-items: center; justify-content: space-between; padding: 10px; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 8px; }
            .slot-item button { background-color: #007bff; color: white; padding: 5px 10px; font-size: 12px; }
            .slot-item button:disabled { background-color: #ccc; cursor: not-allowed; }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>ご希望日時の選択</h1>
            <p>お名前をご入力後、下の候補リストからご希望の日時を最大3つまで、希望する順番で選択してください。</p>
            <hr>
    
            <form id="booking-form">
                <div class="form-group">
                    <label for="customer-name">お名前</label>
                    <input type="text" id="customer-name" name="customer_name" placeholder="例:山田 太郎" required>
                </div>
    
                <div id="selected-choices-area">
                    <h2>ご希望日時(希望順)</h2>
                    <div class="choice-slot" id="choice-box-1">
                        <span class="label">第1希望:</span>
                        <span class="value"><span class="placeholder">未選択</span></span>
                        <span class="actions"></span>
                    </div>
                    <div class="choice-slot" id="choice-box-2">
                        <span class="label">第2希望:</span>
                        <span class="value"><span class="placeholder">未選択</span></span>
                        <span class="actions"></span>
                    </div>
                    <div class="choice-slot" id="choice-box-3">
                        <span class="label">第3希望:</span>
                        <span class="value"><span class="placeholder">未選択</span></span>
                        <span class="actions"></span>
                    </div>
                </div>
    
                <div id="slot-list-area">
                    <h2>候補リスト</h2>
                     <? if (finalSlots.length > 0) { ?>
                        <? for (var i = 0; i < finalSlots.length; i++) { 
                            var slotValue = finalSlots[i].toISOString();
                            var slotText = finalSlots[i].toLocaleString('ja-JP', { timeZone: 'Asia/Tokyo', year: 'numeric', month: 'long', day: 'numeric', weekday: 'short', hour: '2-digit', minute: '2-digit' });
                        ?>
                            <div class="slot-item" data-slot-value="<?= slotValue ?>">
                                <span class="slot-text"><?= slotText ?></span>
                                <button type="button" onclick="selectSlot('<?= slotValue ?>', '<?= slotText ?>', this)">選択</button>
                            </div>
                        <? } ?>
                    <? } else { ?>
                        <p>提示された日程はありません。</p>
                    <? } ?>
                </div>
    
                <button type="submit" class="submit-btn">この内容で依頼する</button>
            </form>
    
            <div id="loading" style="display:none; text-align:center; margin-top:20px;"><p>送信中です...</p></div>
            <div id="success-message" style="display:none; text-align:center;">
                <h2>ありがとうございました</h2>
                <p>リクエストを受け付けました。確定のご連絡をお待ちください。</p>
            </div>
        </div>
    
        <script>
            const selectedChoices = []; // 選択された日時のISO文字列を順番に保持する配列
    
            function selectSlot(slotValue, slotText, buttonElement) {
                if (selectedChoices.length >= 3) {
                    alert('希望日時は3つまで選択できます。');
                    return;
                }
    
                selectedChoices.push(slotValue);
                buttonElement.disabled = true;
    
                updateChoiceDisplay();
            }
    
            function removeChoice(index) {
                const removedValue = selectedChoices[index];
                selectedChoices.splice(index, 1);
                
                const slotItem = document.querySelector(`.slot-item[data-slot-value="${removedValue}"]`);
                if (slotItem) {
                    slotItem.querySelector('button').disabled = false;
                }
                
                updateChoiceDisplay();
            }
    
            function updateChoiceDisplay() {
                for (let i = 1; i <= 3; i++) {
                    const choiceBox = document.getElementById(`choice-box-${i}`);
                    const valueEl = choiceBox.querySelector('.value');
                    const actionsEl = choiceBox.querySelector('.actions');
    
                    if (i - 1 < selectedChoices.length) {
                        const slotValue = selectedChoices[i - 1];
                        const slotItem = document.querySelector(`.slot-item[data-slot-value="${slotValue}"]`);
                        const slotText = slotItem.querySelector('.slot-text').textContent;
                        
                        valueEl.textContent = slotText;
                        actionsEl.innerHTML = `<button type="button" onclick="removeChoice(${i - 1})">削除</button>`;
                    } else {
                        valueEl.innerHTML = '<span class="placeholder">未選択</span>';
                        actionsEl.innerHTML = '';
                    }
                }
            }
    
            document.getElementById('booking-form').addEventListener('submit', function(e) {
                e.preventDefault();
    
                if (selectedChoices.length === 0) {
                    alert('ご希望日時を1つ以上選択してください。');
                    return;
                }
    
                this.style.display = 'none';
                document.getElementById('loading').style.display = 'block';
    
                const formData = new FormData(this);
                const bookingData = {
                    name: formData.get('customer_name'),
                    choices: selectedChoices
                };
    
                google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).processBooking(bookingData);
            });
            
            function onSuccess(response) {
                document.getElementById('loading').style.display = 'none';
                document.getElementById('success-message').style.display = 'block';
            }
    
            function onFailure(error) {
                document.getElementById('loading').style.display = 'none';
                document.getElementById('booking-form').style.display = 'block';
                alert('エラーが発生しました: ' + error.message);
            }
        </script>
    </body>
    </html>
     
     
    LINE自動化しています。GASが得意です。 業務効率化の実装を行っています。 補助金無料サポートも行います。 小規模でも導入できる現実的な仕組みづくりを支援。設計から実装まで伴走します。 https://pet-salon-suita.vercel.app/

    あなたへのおすすめ