AWSTemplateFormatVersion: "2010-09-09"
Description: "CFT for Amazon Connect video calling via Task"
Parameters:
  ConnectInstanceARN:
    Type: String
    Description: Enter Amazon Connect Instance ARN
    Default: "<your-connect-instance-ARN>"
  ConnectInstanceID:
    Type: String
    Description: Enter Amazon Connect Instance ID
    Default: "<your-connect-instance-ID>"
  OriginationNumber:
    Type: String
    Description: Enter Origination Number Or SenderId
    Default: "<your-origination-number-or-senderId>"

Resources:
  S3Bucket:
    DeletionPolicy: "Delete"
    Metadata:
      Comment: "Bucket to store some data"
    Properties:
      AccessControl: "Private"
      BucketName: !Sub "cf-simple-s3-origin-${AWS::StackName}-${AWS::AccountId}"
      WebsiteConfiguration:
        ErrorDocument: error.html
        IndexDocument: index.html
    Type: AWS::S3::Bucket

  S3BucketPolicy:
    Metadata:
      Comment: "Bucket policy to allow cloudfront to access the data"
    Properties:
      Bucket: !Ref S3Bucket
      PolicyDocument:
        Statement:
          - Action:
              - "s3:GetObject"
            Effect: "Allow"
            Principal:
              CanonicalUser: !GetAtt CfOriginAccessIdentity.S3CanonicalUserId
            Resource:
              - !Sub "arn:aws:s3:::${S3Bucket}/*"
    Type: AWS::S3::BucketPolicy

  CfDistribution:
    Metadata:
      Comment: "A simple CloudFront distribution with an S3 origin"
    Properties:
      DistributionConfig:
        Comment: "A simple distribution with an S3 origin"
        DefaultCacheBehavior:
          AllowedMethods:
            - "HEAD"
            - "GET"
          CachedMethods:
            - "HEAD"
            - "GET"
          Compress: false
          DefaultTTL: 86400
          ForwardedValues:
            Cookies:
              Forward: "none"
            Headers:
              - "Origin"
            QueryString: false
          MaxTTL: 31536000
          MinTTL: 86400
          TargetOriginId: !Sub "s3-origin-${S3Bucket}"
          ViewerProtocolPolicy: "redirect-to-https"
        DefaultRootObject: "index.html"
        Enabled: true
        HttpVersion: "http1.1"
        IPV6Enabled: false
        Origins:
          - DomainName: !GetAtt S3Bucket.DomainName
            Id: !Sub "s3-origin-${S3Bucket}"
            OriginPath: ""
            S3OriginConfig:
              OriginAccessIdentity: !Sub "origin-access-identity/cloudfront/${CfOriginAccessIdentity}"
        PriceClass: "PriceClass_All"
    Type: AWS::CloudFront::Distribution

  CfOriginAccessIdentity:
    Metadata:
      Comment: "Access S3 bucket content only through CloudFront"
    Properties:
      CloudFrontOriginAccessIdentityConfig:
        Comment: "Access S3 bucket content only through CloudFront"
    Type: AWS::CloudFront::CloudFrontOriginAccessIdentity

  SendSMSDataTable:
    Type: AWS::DynamoDB::Table
    Properties:
      KeySchema:
        - AttributeName: contactID
          KeyType: HASH
      AttributeDefinitions:
        - AttributeName: contactID
          AttributeType: S
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
      TableName: send-sms-data-table
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete

  LambdaSendSMSOperationIAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
      Policies:
        - PolicyName: SendSMSLambda_Policy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - connect:ListUsers
                  - sms-voice:SendTextMessage
                  - dynamodb:*
                Resource: "*"

  LambdaScanOperationIAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
      Policies:
        - PolicyName: ScanVideoCallingDataLambda_Policy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - dynamodb:*
                Resource: "*"

  LambdaSendSMSOperation:
    Type: "AWS::Lambda::Function"
    Properties:
      Runtime: "python3.12"
      RuntimeManagementConfig:
        UpdateRuntimeOn: "Auto"
      ReservedConcurrentExecutions: 10
      Description: "Lambda Function to send SMS to end user with URL and PIN data "
      Handler: "index.lambda_handler"
      MemorySize: 128
      Timeout: 60
      Role: !GetAtt LambdaSendSMSOperationIAMRole.Arn
      Code:
        ZipFile: |

          import os
          import boto3
          import random
          import time
          from datetime import datetime, timedelta

          from botocore.exceptions import ClientError

          def lambda_handler(event, context):

              dynamodb = boto3.resource('dynamodb', region_name='eu-west-2')
              table = dynamodb.Table(os.environ['DYNAMODB_TABLE_NAME'])
              connect_client = boto3.client('connect')
              contact_data = event['Details']['ContactData']
              contact_id = contact_data['ContactId']  # Get the contactId from the event
              agent_login = contact_data['References']['agent_login']['Value']  # Get the agent name from the event
              PIN = random.randint(100, 999) # nosec
              customer_number = contact_data['References']['Customer_Number']['Value']
              instance_id = os.environ['INSTANCE_ID']

              response = connect_client.list_users(
                  InstanceId=instance_id,
              )

              if response:
                  usernames = [user['Username'] for user in response['UserSummaryList']]
                  if agent_login in usernames:
                      expire_timestamp = int((datetime.now() + timedelta(minutes=30)).timestamp())
                      item = {
                          'contactID': contact_id,  # Use contactId as the primary key
                          'agent_name': agent_login,
                          'PIN': PIN,
                          'customer_number': customer_number,
                          'status': 'video call pending',
                          'sms_timestamp':datetime.now().isoformat(),
                          'expire':expire_timestamp
                      }

                      try:
                          table.put_item(Item=item)
                          print(f"Item added to DynamoDB: {item}")
                          main(PIN, customer_number)
                          return {
                              'statusCode': 200,
                              'body': 'Item added to DynamoDB successfully.'
                          }
                          
                      except Exception as e:
                          return {
                              'statusCode': 500,
                              'body': f'Error adding item to DynamoDB: {str(e)}'
                          }
                  else:
                      print("Agent login not found in the search user response")
              else:
                  print("No ContactFlowId or ContactFlowModuleId provided")

              # main()

          def send_sms_message(sms_voice_v2_client, configuration_set, context_keys,
                              country_parameters, destination_number, dry_run, keyword,
                              max_price, message_body, message_type, origination_number,
                              ttl):
              try:
                  response = sms_voice_v2_client.send_text_message(
                      # ConfigurationSetName=configuration_set,
                      Context=context_keys,
                      DestinationCountryParameters=country_parameters,
                      DestinationPhoneNumber=destination_number,
                      DryRun=dry_run,
                      # Keyword=keyword,
                      MaxPrice=max_price,
                      MessageBody=message_body,
                      MessageType=message_type,
                      OriginationIdentity=origination_number,
                      TimeToLive=ttl
                  )

              except ClientError as e:
                  print(e.response)
              else:
                  return response['MessageId']

          def main(PIN, customer_number):
              configuration_set = "MyConfigurationSet"
              context_keys = {"key1": "value1"}
              country_parameters = {}
              destination_number = "+44"+ customer_number
              dry_run = False
              keyword = "MyKeyword"
              max_price = "2.00"
              video_link_url = os.environ['VIDEO_LINK_URL']
              message_body = f"ABC Corp has invited you to a video call. Tap the link below to start it. \n{video_link_url}\nPin: {PIN}"
              message_type = "TRANSACTIONAL"
              origination_number = os.environ['ORIGINATION_NUMBER']
              ttl = 120

              print(f"Sending text message to {destination_number}.")

              message_id = send_sms_message(
                  boto3.client('pinpoint-sms-voice-v2'), configuration_set, context_keys,
                  country_parameters, destination_number, dry_run, keyword, max_price,
                  message_body, message_type, origination_number, ttl)

              print(f"Message sent!\nMessage ID: {message_id}")

          if __name__ == '__main__':
              main(PIN)
      Environment:
        Variables:
          DYNAMODB_TABLE_NAME:
            Ref: SendSMSDataTable
          INSTANCE_ID:
            Ref: ConnectInstanceID
          ORIGINATION_NUMBER:
            Ref: OriginationNumber
          VIDEO_LINK_URL: !GetAtt CfDistribution.DomainName

  LambdafirstIntegrationAssociation:
    Type: AWS::Connect::IntegrationAssociation
    Properties:
      InstanceId: !Ref ConnectInstanceARN
      IntegrationType: LAMBDA_FUNCTION
      IntegrationArn: !GetAtt LambdaSendSMSOperation.Arn

  ConnectContactFlowFirst:
    Type: AWS::Connect::ContactFlow
    Properties:
      Name: "Send SMS Via Task"
      InstanceArn: !Ref ConnectInstanceARN
      Type: "CONTACT_FLOW"
      Content: !Sub
        - '{ "Version": "2019-10-30", "StartAction": "73371ca2-13ec-4ac8-95a5-47b88db1b0c5", "Metadata": { "entryPointPosition": { "x": 40, "y": 40 }, "ActionMetadata": { "a114767c-e1b9-4221-a2d7-d7a740e6c818": { "position": { "x": 755.2, "y": 184 } }, "4d69c80c-d942-465d-8e5f-50064d00897f": { "position": { "x": 534.4, "y": 126.4 }, "parameters": { "LambdaFunctionARN": { "useDynamic": true }, "LambdaInvocationAttributes": { "test123": { "useDynamic": true } } }, "dynamicMetadata": { "test123": true }, "useDynamic": true }, "73371ca2-13ec-4ac8-95a5-47b88db1b0c5": { "position": { "x": 112.8, "y": 324 } }, "21da04ed-f1a9-49bc-9d51-8b219f6bfd1d": { "position": { "x": 400.8, "y": 517.6 }, "dynamicParams": [] } }, "Annotations": [], "name": "Send SMS Via Task", "description": "Contact Flow to trigger SMS to user phone", "type": "contactFlow", "status": "PUBLISHED", "hash": {} }, "Actions": [ { "Parameters": {}, "Identifier": "a114767c-e1b9-4221-a2d7-d7a740e6c818", "Type": "DisconnectParticipant", "Transitions": {} }, { "Parameters": { "LambdaFunctionARN": "$.Attributes.LambdaArn", "InvocationTimeLimitSeconds": "8", "LambdaInvocationAttributes": { "test123": "$.Agent.ARN" }, "ResponseValidation": { "ResponseType": "STRING_MAP" } }, "Identifier": "4d69c80c-d942-465d-8e5f-50064d00897f", "Type": "InvokeLambdaFunction", "Transitions": { "NextAction": "a114767c-e1b9-4221-a2d7-d7a740e6c818", "Errors": [ { "NextAction": "a114767c-e1b9-4221-a2d7-d7a740e6c818", "ErrorType": "NoMatchingError" } ] } }, { "Parameters": { "FlowLoggingBehavior": "Enabled" }, "Identifier": "73371ca2-13ec-4ac8-95a5-47b88db1b0c5", "Type": "UpdateFlowLoggingBehavior", "Transitions": { "NextAction": "21da04ed-f1a9-49bc-9d51-8b219f6bfd1d" } }, { "Parameters": { "Attributes": { "LambdaArn": "${LambdaArn}" }, "TargetContact": "Current" }, "Identifier": "21da04ed-f1a9-49bc-9d51-8b219f6bfd1d", "Type": "UpdateContactAttributes", "Transitions": { "NextAction": "4d69c80c-d942-465d-8e5f-50064d00897f", "Errors": [ { "NextAction": "4d69c80c-d942-465d-8e5f-50064d00897f", "ErrorType": "NoMatchingError" } ] } } ] }'
        - LambdaArn: !GetAtt LambdaSendSMSOperation.Arn

  LambdaScanOperation:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: "python3.12"
      RuntimeManagementConfig:
        UpdateRuntimeOn: "Auto"
      ReservedConcurrentExecutions: 10
      Description: "Lambda Function that scans DynamoDB table for video calling data"
      Handler: "index.lambda_handler"
      MemorySize: 128
      Timeout: 60
      Role: !GetAtt LambdaScanOperationIAMRole.Arn
      Code:
        ZipFile: |


          import boto3
          import os
          import json
          from datetime import datetime, timedelta

          def lambda_handler(event, context):
              print("Received event:")
              print(event)
              dynamodb = boto3.resource('dynamodb', region_name='eu-west-2')
              table = dynamodb.Table(os.environ['DYNAMODB_TABLE_NAME'])
              print(table)
              # Get the PIN from the event
              pin = int(event.get('Details', {}).get('Parameters', {}).get('pin'))
              print(pin)
              if not pin:
                  print("PIN not provided in the event")
                  return {'error': 'PIN not provided in the event'}

              try:
                  print(f"Scanning DynamoDB table for PIN: {pin}")
                  # Scan the table based on the PIN
                  response = table.scan(
                      FilterExpression=boto3.dynamodb.conditions.Attr('PIN').eq(pin)
                  )
                  items = response['Items']

                  if items:
                      print("Items found:")
                      item = items[0]
                      print(item)  # Print each item as JSON with indentation

                      # Check the sms_timestamp
                      sms_timestamp = item.get('sms_timestamp')
                      if sms_timestamp:
                          sms_datetime = datetime.fromisoformat(sms_timestamp)
                          current_datetime = datetime.now()

                          # Check if the current time is within 5 minute of the sms_timestamp
                          one_minute_ago = current_datetime - timedelta(minutes=5)
                          if one_minute_ago <= sms_datetime <= current_datetime:
                              # Update the status to "successful"
                              item['status'] = 'successful'
                              table.update_item(
                                  Key={'contactID': item['contactID']},
                                  UpdateExpression='SET #status = :status',
                                  ExpressionAttributeNames={'#status': 'status'},
                                  ExpressionAttributeValues={':status': 'video call completed'}
                              )
                              return item
                          else:
                              return {'message': 'Sorry, the SMS has expired'}
                      else:
                          return {'error': 'sms_timestamp not found in the item'}
                  else:
                      print("No items found with the given PIN")
                      return {'message': 'No items found with the given PIN'}
              except Exception as e:
                  print(f"Error occurred: {str(e)}")
                  return {'error': str(e)}
      Environment:
        Variables:
          DYNAMODB_TABLE_NAME:
            Ref: SendSMSDataTable

  LambdasecondIntegrationAssociation:
    Type: AWS::Connect::IntegrationAssociation
    Properties:
      InstanceId: !Ref ConnectInstanceARN
      IntegrationType: LAMBDA_FUNCTION
      IntegrationArn: !GetAtt LambdaScanOperation.Arn

  ConnectContactFlowSecond:
    Type: AWS::Connect::ContactFlow
    Properties:
      Name: "VideoCalling"
      InstanceArn: !Ref ConnectInstanceARN
      Type: "CONTACT_FLOW"
      Content: !Sub
        - '{"Version": "2019-10-30","StartAction": "44082699-a1c3-4379-836c-a62c728c5326","Metadata": {"entryPointPosition": {"x": -112,"y": 128},"ActionMetadata": {"9841bdde-a25a-4f40-b86b-4d10f38db441": {"position": {"x": -24.8,"y": 235.2},"children": ["eea7b01c-8029-49fd-a02a-246d1ed6f808"],"overrideConsoleVoice": true,"fragments": {"SetContactData": "eea7b01c-8029-49fd-a02a-246d1ed6f808"},"overrideLanguageAttribute": true},"eea7b01c-8029-49fd-a02a-246d1ed6f808": {"position": {"x": -24.8,"y": 235.2},"dynamicParams": []},"44082699-a1c3-4379-836c-a62c728c5326": {"position": {"x": 4.8,"y": -114.4}},"10d3d317-49f7-41ac-9861-b5afa609ca30": {"position": {"x": 17.6,"y": 67.2}},"af502a02-5558-4bc9-95c1-41c1584bec2f": {"position": {"x": 1109.6,"y": 301.6}},"45e69880-8b56-45cf-b930-2c7c28fbfd7a": {"position": {"x": 1041.6,"y": 53.6}},"3351dd44-8fe6-4c64-b2e4-b2492c55d99f": {"position": {"x": 691.2,"y": 403.2}},"31696256-cc75-4e51-a4d3-9c64e868c485": {"position": {"x": 402.4,"y": 906.4}},"ec186434-e9d9-420d-96cf-02fc61bacc55": {"position": {"x": 659.2,"y": 55.2},"parameters": {"AgentId": {"useDynamic": true}},"useDynamic": true},"7d6b98e5-6b19-4dd3-b09f-926f8f0c9115": {"position": {"x": 362.4,"y": 652.8},"conditions": [],"conditionMetadata": [{"id": "3256a07f-30a8-4f1e-9aab-7eabc1f655fc","operator": {"name": "Equals","value": "Equals","shortDisplay": "="},"value": "successful"}]},"a7ac899f-1d08-4cdf-8179-6cc6cbe0d8ac": {"position": {"x": -16.8,"y": 467.2},"dynamicParams": []},"84cf4be6-40e1-47e8-aa6c-b128474e7ef8": {"position": {"x": -44.8,"y": 1012},"dynamicParams": []},"e22761a9-58b6-425e-8dac-8afbe9718f84": {"position": {"x": -57.6,"y": 715.2},"conditionMetadata": [],"countryCodePrefix": "+1"},"6ebed6a1-6402-4a4a-9ddf-093c5027a389": {"position": {"x": 312.8,"y": 343.2},"dynamicParams": []},"c460b5c1-6fd0-4938-b008-a1be051a97a6": {"position": {"x": 289.6,"y": -120.8},"dynamicParams": []},"44a71ebd-6b20-484e-b183-f85ba0886349": {"position": {"x": 288.8,"y": 92.8},"parameters": {"LambdaFunctionARN": {"useDynamic": true},"LambdaInvocationAttributes": {"pin": {"useDynamic": true}}},"dynamicMetadata": {"pin": true},"useDynamic": true}},"Annotations": [],"name": "VideoCalling","description": "Contact Flow to invoke video calling ","type": "contactFlow","status": "published","hash": {}},"Actions": [{"Parameters": {"TextToSpeechVoice": "Amy","TextToSpeechEngine": "Neural","TextToSpeechStyle": "Conversational"},"Identifier": "9841bdde-a25a-4f40-b86b-4d10f38db441","Type": "UpdateContactTextToSpeechVoice","Transitions": {"NextAction": "eea7b01c-8029-49fd-a02a-246d1ed6f808","Errors": [{"NextAction": "a7ac899f-1d08-4cdf-8179-6cc6cbe0d8ac","ErrorType": "NoMatchingError"}]}},{"Parameters": {"LanguageCode": "en-GB"},"Identifier": "eea7b01c-8029-49fd-a02a-246d1ed6f808","Type": "UpdateContactData","Transitions": {"NextAction": "a7ac899f-1d08-4cdf-8179-6cc6cbe0d8ac","Errors": [{"NextAction": "a7ac899f-1d08-4cdf-8179-6cc6cbe0d8ac","ErrorType": "NoMatchingError"}]}},{"Parameters": {"FlowLoggingBehavior": "Enabled"},"Identifier": "44082699-a1c3-4379-836c-a62c728c5326","Type": "UpdateFlowLoggingBehavior","Transitions": {"NextAction": "10d3d317-49f7-41ac-9861-b5afa609ca30"}},{"Parameters": {"RecordingBehavior": {"RecordedParticipants": ["Agent","Customer"],"IVRRecordingBehavior": "Disabled"},"AnalyticsBehavior": {"Enabled": "True","AnalyticsLanguage": "en-GB","AnalyticsRedactionBehavior": "Disabled","AnalyticsRedactionResults": "RedactedAndOriginal","ChannelConfiguration": {"Chat": {"AnalyticsModes": []},"Voice": {"AnalyticsModes": ["PostContact"]}},"SentimentConfiguration": {"Enabled": "True"}}},"Identifier": "10d3d317-49f7-41ac-9861-b5afa609ca30","Type": "UpdateContactRecordingBehavior","Transitions": {"NextAction": "9841bdde-a25a-4f40-b86b-4d10f38db441"}},{"Parameters": {"Text": "Sorry, you have exceed the retries. Please try again later."},"Identifier": "af502a02-5558-4bc9-95c1-41c1584bec2f","Type": "MessageParticipant","Transitions": {"NextAction": "45e69880-8b56-45cf-b930-2c7c28fbfd7a","Errors": [{"NextAction": "45e69880-8b56-45cf-b930-2c7c28fbfd7a","ErrorType": "NoMatchingError"}]}},{"Parameters": {},"Identifier": "45e69880-8b56-45cf-b930-2c7c28fbfd7a","Type": "DisconnectParticipant","Transitions": {}},{"Parameters": {},"Identifier": "3351dd44-8fe6-4c64-b2e4-b2492c55d99f","Type": "TransferContactToQueue","Transitions": {"NextAction": "45e69880-8b56-45cf-b930-2c7c28fbfd7a","Errors": [{"NextAction": "45e69880-8b56-45cf-b930-2c7c28fbfd7a","ErrorType": "QueueAtCapacity"},{"NextAction": "45e69880-8b56-45cf-b930-2c7c28fbfd7a","ErrorType": "NoMatchingError"}]}},{"Parameters": {"LoopCount": "2"},"Identifier": "31696256-cc75-4e51-a4d3-9c64e868c485","Type": "Loop","Transitions": {"NextAction": "af502a02-5558-4bc9-95c1-41c1584bec2f","Conditions": [{"NextAction": "84cf4be6-40e1-47e8-aa6c-b128474e7ef8","Condition": {"Operator": "Equals","Operands": ["ContinueLooping"]}},{"NextAction": "af502a02-5558-4bc9-95c1-41c1584bec2f","Condition": {"Operator": "Equals","Operands": ["DoneLooping"]}}]}},{"Parameters": {"AgentId": "$.Attributes.agent_name"},"Identifier": "ec186434-e9d9-420d-96cf-02fc61bacc55","Type": "UpdateContactTargetQueue","Transitions": {"NextAction": "3351dd44-8fe6-4c64-b2e4-b2492c55d99f","Errors": [{"NextAction": "3351dd44-8fe6-4c64-b2e4-b2492c55d99f","ErrorType": "NoMatchingError"}]}},{"Parameters": {"ComparisonValue": "$.Attributes.status"},"Identifier": "7d6b98e5-6b19-4dd3-b09f-926f8f0c9115","Type": "Compare","Transitions": {"NextAction": "31696256-cc75-4e51-a4d3-9c64e868c485","Conditions": [{"NextAction": "ec186434-e9d9-420d-96cf-02fc61bacc55","Condition": {"Operator": "Equals","Operands": ["successful"]}}],"Errors": [{"NextAction": "31696256-cc75-4e51-a4d3-9c64e868c485","ErrorType": "NoMatchingCondition"}]}},{"Parameters": {"Attributes": {"RequestPrompt": "Thank you for contacting ABC Corp. You will soon be transferred to an agent. Please enter the PIN you have received in an SMS."},"TargetContact": "Current"},"Identifier": "a7ac899f-1d08-4cdf-8179-6cc6cbe0d8ac","Type": "UpdateContactAttributes","Transitions": {"NextAction": "e22761a9-58b6-425e-8dac-8afbe9718f84","Errors": [{"NextAction": "e22761a9-58b6-425e-8dac-8afbe9718f84","ErrorType": "NoMatchingError"}]}},{"Parameters": {"Attributes": {"RequestPrompt": "Your PIN is either expired or entered incorrectly. Please try again ."},"TargetContact": "Current"},"Identifier": "84cf4be6-40e1-47e8-aa6c-b128474e7ef8","Type": "UpdateContactAttributes","Transitions": {"NextAction": "e22761a9-58b6-425e-8dac-8afbe9718f84","Errors": [{"NextAction": "e22761a9-58b6-425e-8dac-8afbe9718f84","ErrorType": "NoMatchingError"}]}},{"Parameters": {"StoreInput": "True","InputTimeLimitSeconds": "5","Text": "$.Attributes.RequestPrompt","DTMFConfiguration": {"DisableCancelKey": "False","InterdigitTimeLimitSeconds": "5"},"InputValidation": {"CustomValidation": {"MaximumLength": "3"}}},"Identifier": "e22761a9-58b6-425e-8dac-8afbe9718f84","Type": "GetParticipantInput","Transitions": {"NextAction": "c460b5c1-6fd0-4938-b008-a1be051a97a6","Errors": [{"NextAction": "c460b5c1-6fd0-4938-b008-a1be051a97a6","ErrorType": "NoMatchingError"}]}},{"Parameters": {"Attributes": {"customer_number": "$.External.customer_number","agent_name": "$.External.agent_name","status": "$.External.status"},"TargetContact": "Current"},"Identifier": "6ebed6a1-6402-4a4a-9ddf-093c5027a389","Type": "UpdateContactAttributes","Transitions": {"NextAction": "7d6b98e5-6b19-4dd3-b09f-926f8f0c9115","Errors": [{"NextAction": "7d6b98e5-6b19-4dd3-b09f-926f8f0c9115","ErrorType": "NoMatchingError"}]}},{"Parameters": {"Attributes": {"LambdaArn": "${LambdaArn}"},"TargetContact": "Current"},"Identifier": "c460b5c1-6fd0-4938-b008-a1be051a97a6","Type": "UpdateContactAttributes","Transitions": {"NextAction": "44a71ebd-6b20-484e-b183-f85ba0886349","Errors": [{"NextAction": "44a71ebd-6b20-484e-b183-f85ba0886349","ErrorType": "NoMatchingError"}]}},{"Parameters": {"LambdaFunctionARN": "$.Attributes.LambdaArn","InvocationTimeLimitSeconds": "8","LambdaInvocationAttributes": {"pin": "$.StoredCustomerInput"},"ResponseValidation": {"ResponseType": "JSON"}},"Identifier": "44a71ebd-6b20-484e-b183-f85ba0886349","Type": "InvokeLambdaFunction","Transitions": {"NextAction": "6ebed6a1-6402-4a4a-9ddf-093c5027a389","Errors": [{"NextAction": "6ebed6a1-6402-4a4a-9ddf-093c5027a389","ErrorType": "NoMatchingError"}]}}]}'
        - LambdaArn: !GetAtt LambdaScanOperation.Arn

  TaskTemplate:
    Type: AWS::Connect::TaskTemplate
    Properties:
      Constraints:
        RequiredFields:
          - Id:
              Name: Task name
          - Id:
              Name: Customer_Number
          - Id:
              Name: agent_login
        ReadOnlyFields:
          - Id:
              Name: Task name
          - Id:
              Name: Description
          - Id:
              Name: Schedule
        InvisibleFields:
          - Id:
              Name: Description
          - Id:
              Name: Schedule
      ContactFlowArn: !Ref ConnectContactFlowFirst
      Defaults:
        - Id:
            Name: Task name
          DefaultValue: Send SMS
      Description: ""
      Fields:
        - Id:
            Name: Task name
          Description: The name of the task
          Type: NAME
        - Id:
            Name: Description
          Description: The description of the task
          Type: DESCRIPTION
        - Id:
            Name: Customer_Number
          Description: ""
          Type: NUMBER
        - Id:
            Name: agent_login
          Description: ""
          Type: TEXT
        - Id:
            Name: Schedule
          Description: The scheduled time to complete the task
          Type: SCHEDULED_TIME
      InstanceArn: !Ref ConnectInstanceARN
      Name: VideoCallingTask
      Status: ACTIVE

Outputs:
  S3BucketName:
    Description: "Bucket name"
    Value: !Ref S3Bucket
  CfDistributionId:
    Description: "Id for our cloudfront distribution"
    Value: !Ref CfDistribution
  CfDistributionDomainName:
    Description: "Domain name for our cloudfront distribution"
    Value: !GetAtt CfDistribution.DomainName
