Gestire le richieste di nuove attrezzature per i dipendenti

Livello di codifica: principiante
Durata: 10 minuti
Tipo di progetto: automazione con un trigger basato su eventi e un trigger basato sul tempo

Obiettivi

  • Scopri cosa fa la soluzione.
  • Scopri cosa fanno i servizi Apps Script all'interno della soluzione.
  • Configura lo script.
  • Esegui lo script.

Informazioni su questa soluzione

I nuovi dipendenti di solito richiedono l'accesso al sistema e le attrezzature all'IT. Per gestire queste richieste, puoi creare un modulo con Moduli Google in cui gli utenti possono indicare l'accesso e i dispositivi di cui hanno bisogno. Una volta che l'IT completa la richiesta e ne aggiorna lo stato, i richiedenti ricevono una notifica via email.

Modulo Google per le richieste di attrezzature per i nuovi dipendenti.

Come funziona

Lo script crea un modulo di richiesta di attrezzature. Puoi personalizzare gli elementi del modulo nel codice dello script di esempio. Quando un utente invia il modulo, lo script invia una notifica via email al punto di contatto designato per le richieste. Una volta che lo stato della richiesta nel foglio di lavoro viene modificato in "Completato", lo script invia un'email di conferma alla persona che ha inviato il modulo.

Servizi Apps Script

Questa soluzione utilizza i seguenti servizi:

  • Servizio Moduli: crea il modulo per le richieste IT.
  • Servizio Fogli di lavoro: verifica se il modulo di richiesta esiste già per ridurre i duplicati. Gestisce le risposte del modulo spostandole nei fogli In attesa e Completate in base alle necessità.
  • Servizio Mail: crea e invia le email di notifica di richiesta e completamento.
  • Servizio Script: crea i trigger. Uno viene eseguito quando viene inviato un modulo e l'altro viene eseguito ogni cinque minuti per verificare se lo stato di una richiesta è contrassegnato come "Completato".

Prerequisiti

Per utilizzare questo esempio, devi soddisfare i seguenti prerequisiti:

  • Un Account Google (gli account Google Workspace potrebbero richiedere l'approvazione dell'amministratore).
  • Un browser web con accesso a internet.

Configura lo script

Per configurare lo script:

Crea il progetto Apps Script

  1. Fai clic sul pulsante seguente per creare una copia del foglio di lavoro Gestisci le richieste di attrezzature dei dipendenti. Il progetto Apps Script per questa soluzione è allegato al foglio di lavoro:

    Crea una copia

  2. Fai clic su Estensioni > Apps Script.

  3. Accanto alla variabile REQUEST_NOTIFICATION_EMAIL, sostituisci l'email di esempio con la tua email.

  4. Fai clic su Salva Salva il progetto nell'editor di script di Apps Script.

Configura il foglio di lavoro

  1. Torna al foglio di lavoro e fai clic su Richieste di attrezzature > Configura. Potresti dover aggiornare la pagina per visualizzare questo menu personalizzato.
  2. Quando ti viene richiesto, autorizza lo script. <<../_snippets/oauth.md>>
  3. Fai di nuovo clic su Richieste di attrezzature > Configura.

Esegui lo script

  1. Fai clic su Strumenti > Gestisci modulo > Vai al modulo live.
  2. Compila e invia il modulo.
  3. Controlla la tua email per una notifica relativa alla richiesta di attrezzature.
  4. Torna al foglio di lavoro e, nel foglio Richieste in attesa , modifica lo stato della richiesta in Completata.
  5. Entro 5 minuti, lo script invia un'altra email per informarti che la richiesta è stata completata. Lo script sposta la richiesta dal foglio Richieste in attesa al foglio Richieste completate.

Esamina il codice

Per esaminare il codice Apps Script per questa soluzione, fai clic su Visualizza codice sorgente:

Visualizza codice sorgente

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>

Collaboratori

Questo esempio è gestito da Google con l'aiuto di Esperti Google Developers.

Passaggi successivi