Geräteanfragen neuer Mitarbeiter verwalten

Programmierkenntnisse: Anfänger
Dauer: 10 Minuten
Projekttyp: Automatisierung mit einem ereignisgesteuerten Trigger und einem zeitgesteuerten Trigger

Ziele

  • Verstehen, was die Lösung tut.
  • Verstehen, wie die Apps Script-Dienste in der Lösung funktionieren.
  • Das Script einrichten.
  • Das Script ausführen.

Informationen zu dieser Lösung

Neue Mitarbeiter benötigen in der Regel Systemzugriff und Geräte von der IT-Abteilung. Um diese Anfragen zu verwalten, können Sie in Google Formulare ein Formular erstellen, in dem Nutzer angeben können, welchen Zugriff und welche Geräte Mitarbeiter benötigen. Sobald die IT-Abteilung die Anfrage bearbeitet und den Status aktualisiert hat, erhalten die Antragsteller eine E‑Mail-Benachrichtigung.

Google-Formular für Anfragen von neuen Mitarbeitern zur Ausstattung.

Funktionsweise

Das Script erstellt ein Formular für Geräteanfragen. Sie können die Elemente im Formular im Code des Beispielscripts anpassen. Wenn jemand das Formular einreicht, sendet das Script eine E‑Mail-Benachrichtigung an den zuständigen Ansprechpartner für Anfragen. Sobald der Status der Anfrage in der Tabelle in „Abgeschlossen“ geändert wird, sendet das Script eine Bestätigungs-E‑Mail an die Person, die das Formular eingereicht hat.

Apps Script-Dienste

In dieser Lösung werden die folgenden Dienste verwendet:

  • Formulare-Dienst: Erstellt das Formular für IT-Anfragen.
  • Tabellen-Dienst: Prüft, ob das Anfrageformular bereits vorhanden ist, um Duplikate zu vermeiden. Verwaltet die Formularantworten, indem sie bei Bedarf in die Tabellenblätter Ausstehend und Abgeschlossen verschoben werden.
  • E‑Mail-Dienst: Erstellt und sendet die E‑Mails mit der Anfrage und der Benachrichtigung über den Abschluss.
  • Script-Dienst: Erstellt die Trigger. Einer wird ausgelöst, wenn ein Formular eingereicht wird, und der andere wird alle fünf Minuten ausgeführt, um zu prüfen, ob der Status einer Anfrage als „Abgeschlossen“ markiert ist.

Vorbereitung

Für die Verwendung dieses Beispiels müssen die folgenden Voraussetzungen erfüllt sein:

  • Ein Google-Konto (für Google Workspace-Konten ist möglicherweise die Genehmigung durch den Administrator erforderlich).
  • Ein Webbrowser mit Internetzugriff.

Script einrichten

Führen Sie die folgenden Schritte aus, um das Script einzurichten.

Apps Script-Projekt erstellen

  1. Klicken Sie auf die folgende Schaltfläche, um eine Kopie der Tabelle Manage employee equipment requests zu erstellen. Das Apps Script-Projekt für diese Lösung ist an die Tabelle angehängt:

    Kopie erstellen

  2. Klicken Sie auf Erweiterungen > Apps Script.

  3. Ersetzen Sie neben der Variablen REQUEST_NOTIFICATION_EMAIL die Beispiel-E‑Mail-Adresse durch Ihre E‑Mail-Adresse.

  4. Klicken Sie auf „Speichern“ Projekt im Apps Script-Editor speichern.

Tabelle einrichten

  1. Kehren Sie zur Tabelle zurück und klicken Sie auf Equipment requests > Set up. Möglicherweise müssen Sie die Seite aktualisieren, damit dieses benutzerdefinierte Menü angezeigt wird.
  2. Autorisieren Sie die Skripts, wenn Sie dazu aufgefordert werden. <<../_snippets/oauth.md>>
  3. Klicken Sie noch einmal auf Equipment requests > Set up.

Das Script ausführen.

  1. Klicken Sie auf Tools > Formular verwalten > Live-Formular aufrufen.
  2. Füllen Sie das Formular aus und senden Sie es.
  3. In Ihrem E‑Mail-Posteingang sollte eine Benachrichtigung über die Geräteanfrage eingegangen sein.
  4. Kehren Sie zur Tabelle zurück und ändern Sie im Tabellenblatt Ausstehende Anfragen den Status der Anfrage in Abgeschlossen.
  5. Innerhalb von 5 Minuten sendet das Script eine weitere E‑Mail, in der Sie darüber informiert werden, dass die Anfrage abgeschlossen wurde. Das Script verschiebt die Anfrage vom Tabellenblatt Ausstehende Anfragen in das Tabellenblatt Abgeschlossene Anfragen.

Code ansehen

Wenn Sie den Apps Script-Code für diese Lösung ansehen möchten, klicken Sie auf Quellcode ansehen:

Quellcode ansehen

Code.gs

solutions/automations/equipment-requests/Code.js
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/samples/automations/equipment-requests

/*
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Update this variable with the email address you want to send equipment requests to.
const REQUEST_NOTIFICATION_EMAIL = "request_intake@example.com";

// Update the following variables with your own equipment options.
const AVAILABLE_LAPTOPS = [
  '15" high Performance Laptop (OS X)',
  '15" high Performance Laptop (Windows)',
  '15" high performance Laptop (Linux)',
  '13" lightweight laptop (Windows)',
];
const AVAILABLE_DESKTOPS = [
  "Standard workstation (Windows)",
  "Standard workstation (Linux)",
  "High performance workstation (Windows)",
  "High performance workstation (Linux)",
  "Mac Pro (OS X)",
];
const AVAILABLE_MONITORS = ['Single 27"', 'Single 32"', 'Dual 24"'];

// Form field titles, used for creating the form and as keys when handling
// responses.
/**
 * Adds a custom menu to the spreadsheet.
 */
function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu("Equipment requests")
    .addItem("Set up", "setup_")
    .addItem("Clean up", "cleanup_")
    .addToUi();
}

/**
 * Creates the form and triggers for the workflow.
 */
function setup_() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  if (ss.getFormUrl()) {
    const msg = "Form already exists. Unlink the form and try again.";
    SpreadsheetApp.getUi().alert(msg);
    return;
  }
  const form = FormApp.create("Equipment Requests")
    .setCollectEmail(true)
    .setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId())
    .setLimitOneResponsePerUser(false);
  form.addTextItem().setTitle("Employee name").setRequired(true);
  form.addTextItem().setTitle("Desk location").setRequired(true);
  form.addDateItem().setTitle("Due date").setRequired(true);
  form.addListItem().setTitle("Laptop").setChoiceValues(AVAILABLE_LAPTOPS);
  form.addListItem().setTitle("Desktop").setChoiceValues(AVAILABLE_DESKTOPS);
  form.addListItem().setTitle("Monitor").setChoiceValues(AVAILABLE_MONITORS);

  // Hide the raw form responses.
  for (const sheet of ss.getSheets()) {
    if (sheet.getFormUrl() === ss.getFormUrl()) {
      sheet.hideSheet();
    }
  }
  // Start workflow on each form submit
  ScriptApp.newTrigger("onFormSubmit_").forForm(form).onFormSubmit().create();
  // Archive completed items every 5m.
  ScriptApp.newTrigger("processCompletedItems_")
    .timeBased()
    .everyMinutes(5)
    .create();
}

/**
 * Cleans up the project (stop triggers, form submission, etc.)
 */
function cleanup_() {
  const formUrl = SpreadsheetApp.getActiveSpreadsheet().getFormUrl();
  if (!formUrl) {
    return;
  }
  for (const trigger of ScriptApp.getProjectTriggers()) {
    ScriptApp.deleteTrigger(trigger);
  }
  FormApp.openByUrl(formUrl).deleteAllResponses().setAcceptingResponses(false);
}

/**
 * Handles new form submissions to trigger the workflow.
 *
 * @param {Object} event - Form submit event
 */
function onFormSubmit_(event) {
  const response = mapResponse_(event.response);
  sendNewEquipmentRequestEmail_(response);
  const equipmentDetails = Utilities.formatString(
    "%s\n%s\n%s",
    response.Laptop,
    response.Desktop,
    response.Monitor,
  );
  const row = [
    "New",
    "",
    response["Due date"],
    response["Employee name"],
    response["Desk location"],
    equipmentDetails,
    response.email,
  ];
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName("Pending requests");
  sheet.appendRow(row);
}

/**
 * Sweeps completed and cancelled requests, notifying the requestors and archiving them
 * to the completed sheet.
 *
 * @param {Object} event
 */
function processCompletedItems_() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const pending = ss.getSheetByName("Pending requests");
  const completed = ss.getSheetByName("Completed requests");
  const rows = pending.getDataRange().getValues();
  for (let i = rows.length; i >= 2; i--) {
    const row = rows[i - 1];
    const status = row[0];
    if (status === "Completed" || status === "Cancelled") {
      pending.deleteRow(i);
      completed.appendRow(row);
      console.log(`Deleted row: ${i}`);
      sendEquipmentRequestCompletedEmail_({
        "Employee name": row[3],
        "Desk location": row[4],
        email: row[6],
      });
    }
  }
}

/**
 * Sends an email notification that a new equipment request has been submitted.
 *
 * @param {Object} request - Request details
 */
function sendNewEquipmentRequestEmail_(request) {
  const template = HtmlService.createTemplateFromFile(
    "new-equipment-request.html",
  );
  template.request = request;
  template.sheetUrl = SpreadsheetApp.getActiveSpreadsheet().getUrl();
  const msg = template.evaluate();
  MailApp.sendEmail({
    to: REQUEST_NOTIFICATION_EMAIL,
    subject: "New equipment request",
    htmlBody: msg.getContent(),
  });
}

/**
 * Sends an email notifying the requestor that the request is complete.
 *
 * @param {Object} request - Request details
 */
function sendEquipmentRequestCompletedEmail_(request) {
  const template = HtmlService.createTemplateFromFile("request-complete.html");
  template.request = request;
  const msg = template.evaluate();
  MailApp.sendEmail({
    to: request.email,
    subject: "Equipment request completed",
    htmlBody: msg.getContent(),
  });
}

/**
 * Converts a form response to an object keyed by the item titles. Allows easier
 * access to response values.
 *
 * @param {FormResponse} response
 * @return {Object} Form values keyed by question title
 */
function mapResponse_(response) {
  const initialValue = {
    email: response.getRespondentEmail(),
    timestamp: response.getTimestamp(),
  };
  return response.getItemResponses().reduce((obj, itemResponse) => {
    const key = itemResponse.getItem().getTitle();
    obj[key] = itemResponse.getResponse();
    return obj;
  }, initialValue);
}
</section>
<section>
  <h3>new-equipment-request.html</h3>
solutions/automations/equipment-requests/new-equipment-request.html
<!DOCTYPE html>
<!--
 Copyright 2022 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<html>
  <body>
    <p>
    A new equipment request has been made by <?= request.email ?>.
    </p>

    <p>
    Employee name: <?= request['Employee name'] ?><br/>
    Desk location name: <?= request['Desk location'] ?><br/>
    Due date: <?= request['Due date'] ?><br/>
    Laptop model: <?= request['Laptop'] ?><br/>
    Desktop model: <?= request['Desktop'] ?><br/>
    Monitor(s): <?= request['Monitor'] ?><br/>
    </p>

    See <a href="<?= sheetUrl ?>">the spreadsheet</a> to take or assign this item.
  </body>
</html>
</section>
<section>
  <h3>request-complete.html</h3>
solutions/automations/equipment-requests/request-complete.html
<!DOCTYPE html>
<!--
 Copyright 2022 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<html>
  <body>
    <p>
    An equipment request has been completed.
    </p>

    <p>
    Employee name: <?= request['Employee name'] ?><br/>
    Desk location name: <?= request['Desk location'] ?><br/>
    </p>
  </body>
</html>
</section>

Beitragende

Dieses Beispiel wird von Google mit Unterstützung von Google Developer Experts verwaltet.

Nächste Schritte