## Microsoft Teams

Integrating Microsoft Teams into your Node.js backend and React frontend application can enhance communication and workflow efficiency,
especially in a body shop management context for the automotive industry. Microsoft Teams provides several ways to integrate its functionalities into your application, 
including bots, tabs, messaging extensions, webhooks, and connectors. Here's an overview of the options and how to implement them:

### 0.5 - Share to Teams (TM)

- https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/share-to-teams-from-web-apps
- https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/share-to-teams-from-personal-app-or-tab
- https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/device-capabilities/people-picker-capability
- (Example of some Teams code Integrations) https://github.com/microsoft/teams-powerapps-app-templates/

### 1. Microsoft Graph API
The Microsoft Graph API is the gateway to data and intelligence in Microsoft 365, including Teams. It allows you to work with Teams data like channels, messages, and more. You can use it to post status changes back to Teams or read data from Teams to affect your site.

Backend (Node.js): Use the @microsoft/microsoft-graph-client package to make API calls to Teams. You will need to handle authentication with Azure AD, which can be done using the @azure/identity package to get tokens for Graph API requests.

*Implementation Steps*:

Register your application in Azure AD to get the client_id and client_secret.

(Is client_id and client_secret going to be something required for every customer or is it going to be a singleton)
Implement OAuth 2.0 authorization flow to obtain access tokens.
(This will need to be tracked by association to a bodyshop)

bodyshop->Channels | People ->Messages

Use the access token to make requests to the Microsoft Graph API to interact with Teams.

### 2. Webhooks and Connectors
Webhooks allow your application to send notifications to a Teams channel, which is useful for posting status changes. Connectors are a set of predefined webhooks that offer a more integrated experience.

Setup:
In Microsoft Teams, configure an incoming webhook for the channel you want to post messages to.
Use the webhook URL to send JSON payloads from your Node.js backend, which can then be displayed in Teams.


### 3. Bots
Bots in Teams can interact with users to take commands or post information. You can use the Bot Framework along with the Teams activity handler to create bots that can communicate with your React frontend and Node.js backend.

Backend (Node.js): Use the botbuilder package to create and manage your bot's interactions with Teams.

*Implementation Steps*:

Create a bot registration in Azure Bot Services.
Implement the bot logic in your Node.js application using the Bot Framework SDK.
Use the Microsoft Bot Framework's TeamsActivityHandler to respond to Teams-specific activities.

### 4. Tabs
Tabs in Teams allow you to integrate web-based content as part of Teams, which can be your React application or specific parts of it. This is particularly useful for creating a seamless experience within Teams.

*Implementation Steps*:
- Create a Teams app manifest that defines your tab and its configuration.
- Host your React application or the specific parts you want to embed as a tab.
- Use the Teams SDK in your React application to interact with Teams context and APIs.

*Getting Started*:
Microsoft Teams Toolkit for Visual Studio Code: This toolkit simplifies the process of setting up your Teams application, including authentication, configuration, and deployment.
Documentation and Samples: Microsoft provides extensive documentation and sample code for developing Teams applications, which can be invaluable for getting started and solving specific challenges.
Implementing these features requires a good understanding of both the Microsoft Teams platform and your application's architecture. 
Start small, perhaps by implementing notifications via webhooks, and gradually add more complex integrations like bots or tabs based on your needs and user feedback.

### Examples:

##### Posting Messages to a Teams Channel Using Incoming Webhooks

1 - Set up an Incoming Webhook in Microsoft Teams:
- Go to the Teams channel where you want to post messages.
- Click on the three dots (...) next to the channel name and select Connectors.
- Search for Incoming Webhook, click Add, and then Configure.
- Name your webhook, upload an image if desired, and click Create.
- Copy the webhook URL provided.

  (Patrick Note: The clients might have issues with setting up webhooks, it requires a lot of user configuration and our users are not technical).

2 - Node.js Code to Post a Message:

Ensure you have axios or any HTTP client library installed in your Node.js project. If not, you can install axios via npm: npm install axios.
Use the following code snippet to post a message to the Teams channel:

```javascript 
const axios = require('axios');

// Replace 'YOUR_WEBHOOK_URL' with your actual webhook URL
const webhookUrl = 'YOUR_WEBHOOK_URL';

const message = {
  "@type": "MessageCard",
  "@context": "http://schema.org/extensions",
  "summary": "Issue 176715375",
  "themeColor": "0078D7",
  "title": "Issue opened: \"Push notifications not working\"",
  "sections": [{
    "activityTitle": "A new issue was created",
    "activitySubtitle": "Today, 2:36 PM",
    "activityImage": "https://example.com/issues/image.png",
    "facts": [{
        "name": "Repository:",
        "value": "Repo name"
      },
      {
        "name": "Issue #:",
        "value": "176715375"
      }
    ],
    "markdown": true
  }]
};

axios.post(webhookUrl, message)
  .then(response => console.log('Successfully sent message to Teams channel'))
  .catch(error => console.error('Error sending message to Teams channel', error));
```

#### Creating a Simple Bot for Teams
1 Prerequisites:
- Register your bot with the Microsoft Bot Framework and get your bot's App ID and App Password.
- Use the Bot Framework SDK for JavaScript.
  2 Install Dependencies:
- You need to install the botbuilder package. Run npm install botbuilder.

The following example demonstrates a simple bot that echoes back received messages.

```javascript
const { BotFrameworkAdapter, MemoryStorage, ConversationState, TurnContext } = require('botbuilder');

// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about adapters.
const adapter = new BotFrameworkAdapter({
    appId: process.env.MicrosoftAppId,
    appPassword: process.env.MicrosoftAppPassword
});

// Create conversation state with in-memory storage provider.
const conversationState = new ConversationState(new MemoryStorage());
adapter.use(conversationState);

// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
    adapter.processActivity(req, res, async (context) => {
        // Echo back what the user said
        if (context.activity.type === 'message') {
            await context.sendActivity(`You said '${context.activity.text}'`);
        }
    });
});
```

Running Your Bot:
- Make sure to expose your bot endpoint (/api/messages in this case) to the internet using a service like ngrok.
- Update your bot's messaging endpoint in the Microsoft Bot Framework portal to point to the ngrok URL.

### Slash Commands (Bot)
1 -  Create a Microsoft Teams App: You need to develop a Teams app that can interact with users through commands. This involves using the Microsoft Teams Developer Platform and possibly the Bot Framework.
2 - Use Bots for Custom Commands: The primary way to introduce custom slash commands in Teams is through bots. Bots can respond to specific commands (or messages) that are input by users. When you create a bot for Teams, you can define custom commands that the bot will recognize and respond to.
3 - Developing the Bot: You can develop a bot using the Microsoft Bot Framework. This allows your bot to receive and send messages to a Teams channel or chat. Within your bot's code, you can define what actions to take when it receives specific commands.
4 - Register Your Bot with Microsoft Bot Framework: Register your bot with the Microsoft Bot Framework and configure it to work with Microsoft Teams. This step involves getting a Microsoft App ID and password that are necessary for your bot to communicate with the Teams platform.
5 - Add Your Bot to Microsoft Teams: Once your bot is developed and registered, you can package your Teams app (which includes the bot) and upload it to Microsoft Teams. This will make your bot available to users within Teams, where they can interact with it using the custom commands you've defined.
6 - Handling Slash Commands: In the context of your bot's code, you will need to interpret messages that start with a slash (/) as commands. You can then parse the command text and perform the appropriate actions or respond accordingly.
7 - Publish Your App: For broader distribution, you can publish your Teams app to the Teams app store or distribute it within your organization through the Teams admin center.
/ <command> <arb> ....
(Unrelated to teams but then used in teams for functionality)
- A Job has a todo list
- a todo item may have an employee
- a todo item may have a due date
- a todo item may have a priority

--- Call notes ----
- Tasks (TODO List)
- EMail reminders

## Slack

Integrating Slack into your Node.js backend and React frontend application can significantly streamline communication and operations for your automotive industry body shop management software. Slack offers various integration points including bots, apps, webhooks, and its rich API to facilitate interactions between your application and Slack workspace. Here's how you can leverage these integration points:

### 1. **Slack Web API**

The Slack Web API allows you to interact with Slack, enabling functionalities like sending messages, managing channels, and more directly from your application.

- **Backend (Node.js)**: Utilize the `@slack/web-api` package to make API calls from your Node.js backend. This will be the backbone for actions such as posting status updates to Slack channels or handling commands from Slack that can affect your site.

- **Implementation Steps**:
    1. Create a Slack app in your Slack workspace and obtain the API tokens.
    2. Use the `@slack/web-api` package to authenticate and interact with Slack API endpoints.
    3. Implement features such as sending messages or processing events from Slack.

### 2. **Incoming Webhooks**

For simpler integrations focused on sending notifications to Slack channels, incoming webhooks are straightforward and effective. They allow you to send messages to a specific channel without a full-blown app.

- **Setup**:
    1. Create an incoming webhook from the Slack app configuration page.
    2. Use the webhook URL to send messages from your Node.js backend by making simple HTTP POST requests with your message payload.

### 3. **Bots**

Slack bots can facilitate interactive experiences within your Slack workspace, responding to commands, posting notifications, or even pulling data from your site on demand.

- **Backend (Node.js)**: Leverage the `@slack/bolt` framework, which simplifies creating Slack bots with event handling, messaging, and built-in OAuth support.

- **Implementation Steps**:
    1. Create a Slack app and enable bot features.
    2. Use the `@slack/bolt` package to develop your bot, handling events like messages or commands.
    3. Deploy your bot and set it to listen to incoming events from Slack.

### 4. **Slack Block Kit**

For more engaging and interactive messages, Slack's Block Kit provides a UI framework that allows you to create richly formatted messages, modals, and more.

- **Frontend (React)** and **Backend (Node.js)**: Utilize Slack's Block Kit to design complex messages with buttons, sections, and interactive components. You can send these payloads through the Web API or from bots to enhance your app's interaction with users.

### Getting Started

- **Slack API Documentation and Tools**: Slack's API documentation is comprehensive and includes tutorials, tooling (like Block Kit Builder), and SDK documentation to help you get started.

- **Testing and Development**: Slack provides a sandbox environment for you to test your app's integrations and interactions without affecting your live workspace.

To integrate Slack into your application effectively, start by planning out the interactions you need (e.g., notifications, commands, information retrieval) and map these to the appropriate Slack features. Then, incrementally build and test each integration, utilizing Slack's development tools and your existing Node.js and React knowledge to create a seamless experience for your users.

#### Examples

1. Incoming Webhooks
   Incoming Webhooks are a simple way to post messages from your Node.js application into Slack channels. They're perfect for notifying team members about status changes or updates.

Setup:

1 - Create a new Slack app in your workspace and enable incoming webhooks.
2 - Add a new webhook to your app and choose the channel it will post to.
3 - Use the webhook URL to send messages from your backend.

Node.js Example:

```javascript

const axios = require('axios');
const webhookUrl = 'YOUR_SLACK_WEBHOOK_URL';

async function postMessageToSlack(message) {
  await axios.post(webhookUrl, {
    text: message, // Your message here
  });
}

postMessageToSlack('New status update on the automotive project!').catch(console.error);
```
2. Bots
   Slack bots can interact with users via messages, respond to commands, and even post updates. They're great for building interactive features.

Setup:

1 - Create a Slack app and add the Bot Token Scopes (like chat:write).
2 - Install the app to your workspace to get your bot token.
3 - Use the @slack/bolt framework for easy bot development in Node.js.

Node.js Example:

```javascript
const { App } = require('@slack/bolt');

const app = new App({
  token: process.env.SLACK_BOT_TOKEN, // Set your bot's access token here
  signingSecret: process.env.SLACK_SIGNING_SECRET // Set your app's signing secret here
});

app.message('hello', async ({ message, say }) => {
  await say(`Hey there <@${message.user}>!`);
});

(async () => {
  await app.start(process.env.PORT || 3000);
  console.log('Slack bot is running!');
})();
```

3. Slash Commands
   Slash Commands allow users to interact with your application directly from Slack by typing commands that start with /.

Setup:

1 - Create a Slack app and configure a new Slash Command (e.g., /statusupdate).
2 - Point the command request URL to your Node.js backend endpoint.
3 - Implement the endpoint to handle the command and respond accordingly.

Node.js Example:

```javascript
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/slack/commands/statusupdate', (req, res) => {
  const { text, user_name } = req.body; // Command input and user info
  // Logic to handle the command goes here. For example, update a status or fetch information.
  res.send(`Status update received: ${text} - from ${user_name}`);
});

app.listen(process.env.PORT || 3000, () => console.log('Server is running'));
```

4. Interactive Components
   Interactive components like buttons or menus can make your Slack messages more engaging and interactive.

Setup:
1 - Enable Interactivity in your Slack app settings.
2 - Implement an endpoint in your Node.js backend to handle interactions.
3 - Send messages with interactive components from your backend.

Implementing these features into your Node.js and React application will enable a more dynamic and integrated experience for users of your body shop management software. Start with the simpler integrations like webhooks and progressively incorporate bots and interactive components as needed.

ACTION ITEMS:
- Slot in tasks, this will be a dependency for things we want to do in the future.
- This would involve GUI components
- This would involve a backend component