Gestire le richieste di nuove attrezzature per i dipendenti

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

Obiettivi

  • Scopri cosa fa la soluzione.
  • Scoprire cosa fanno i servizi Apps Script con questa soluzione.
  • Configura lo script.
  • Esegui lo script.

Informazioni su questa soluzione

I nuovi dipendenti di solito richiedono l'accesso al sistema e le attrezzature da parte dell'IT. Per gestire queste richieste, puoi creare un modulo con Moduli Google per consentire agli utenti di indicare l'accesso e i dispositivi di cui i dipendenti hanno bisogno. Quando l'IT completa la richiesta e aggiorna il suo stato, i richiedenti ricevono una notifica via email.

Screenshot del modulo di richiesta dell'attrezzatura

Come funziona

Lo script crea un modulo di richiesta dell'apparecchiatura. Puoi personalizzare gli elementi sul modulo nel codice dello script di esempio. Quando qualcuno invia il modulo, lo script invia una notifica via email al punto di contatto designato per le richieste. Quando lo stato della richiesta nel foglio di lavoro passa a "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: consente di verificare se il modulo di richiesta esiste già per mitigare i duplicati. Gestisce le risposte del modulo spostandole nei fogli In attesa e Completati, se necessario.
  • Mail service (Servizio di posta): crea e invia le email di notifica di richiesta e completamento.
  • Servizio di script: crea i trigger. Uno si attiva quando viene inviato un modulo, l'altro ogni cinque minuti per verificare se lo stato di una richiesta è contrassegnato come "Completata".

Prerequisiti

Per utilizzare questo esempio, devi disporre dei 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

Creare 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 il tuo indirizzo email.
  4. Fai clic su Salva Icona Salva.

Imposta 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 richiesto, autorizza lo script. Se nella schermata per il consenso OAuth viene visualizzato l'avviso Questa app non è verificata, continua selezionando Avanzate > Vai a {Nome progetto} (non sicuro).

  3. Fai clic su Richieste di apparecchiature > di nuovo Configura.

Esegui lo script

  1. Fai clic su Strumenti > Gestisci modulo > Vai a modulo pubblicato.
  2. Compila e invia il modulo.
  3. Controlla se nella tua email è presente una notifica relativa alla richiesta dell'attrezzatura.
  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.

Rivedi il codice

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

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_() {
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  if (ss.getFormUrl()) {
    let msg = 'Form already exists. Unlink the form and try again.';
    SpreadsheetApp.getUi().alert(msg);
    return;
  }
  let 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.
  ss.getSheets().forEach(function(sheet) {
    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_() {
  let formUrl = SpreadsheetApp.getActiveSpreadsheet().getFormUrl();
  if (!formUrl) {
    return;
  }
  ScriptApp.getProjectTriggers().forEach(function(trigger) {
    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) {
  let response = mapResponse_(event.response);
  sendNewEquipmentRequestEmail_(response);
  let equipmentDetails = Utilities.formatString('%s\n%s\n%s',
      response['Laptop'],
      response['Desktop'],
      response['Monitor']);
  let row = ['New',
    '',
    response['Due date'],
    response['Employee name'],
    response['Desk location'],
    equipmentDetails,
    response['email']];
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  let 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_() {
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  let pending = ss.getSheetByName('Pending requests');
  let completed = ss.getSheetByName('Completed requests');
  let rows = pending.getDataRange().getValues();
    for (let i = rows.length; i >= 2; i--) {
      let row = rows[i -1];
      let 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) {
  let template = HtmlService.createTemplateFromFile('new-equipment-request.html');
  template.request = request;
  template.sheetUrl = SpreadsheetApp.getActiveSpreadsheet().getUrl();
  let 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) {
  let template = HtmlService.createTemplateFromFile('request-complete.html');
  template.request = request;
  let 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) {
  let initialValue = {
    email: response.getRespondentEmail(),
    timestamp: response.getTimestamp(),
  };
  return response.getItemResponses().reduce(function(obj, itemResponse) {
    let key = itemResponse.getItem().getTitle();
    obj[key] = itemResponse.getResponse();
    return obj;
  }, initialValue);
}

new-equipment-request.html

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>

request-complete.html

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>

Collaboratori

Questo campione è gestito da Google con l'aiuto degli Esperti Google Developers.

Passaggi successivi