1import { Controller } from '@hotwired/stimulus' 2import { Turbo } from '@hotwired/turbo-rails' 3 4export default class extends Controller { 5 static values = { 6 promptForInvalidInstall: Boolean, 7 initialCustomerIdentifier: String, 8 } 9 10 connect() { 11 window.Kustomer.on('context', this._handleContext) 12 window.Kustomer.initialize(this._handleContext) 13 window.Kustomer.resize() 14 } 15 16 _handleContext = (context) => { 17 this.setupKustomerContext(context) 18 } 19 20 setupKustomerContext = async (context) => { 21 const customerId = context.type === 'customer' ? context.id : context.relationships.customer.data.id 22 23 if (this.initialCustomerIdentifierValue === customerId) return 24 if (this.promptForInvalidInstallValue) return 25 26 const { customerEmail } = await this.extractCustomerData(context) 27 const currentUserName = await this.fetchCurrentUserName() 28 29 const params = { 30 email: customerEmail, 31 originating_user_name: currentUserName, 32 } 33 const url = `/kustomer/customers/${customerId}?${this.queryStringWithKustomerParams(params)}` 34 Turbo.visit(url) 35 } 36 37 extractCustomerData = async (context) => { 38 if (context.type === 'customer') { 39 return { 40 customerEmail: context.attributes.emails[0].email, 41 customerId: context.id, 42 } 43 } 44 45 const custId = context.relationships.customer.data.id 46 const custLink = 47 context.relationships.customer.links.self || 48 (custId ? `/v1/customers/${custId}` : null) 49 50 if (!custLink) return '' 51 52 const customer = await new Promise((resolve) => { 53 window.Kustomer.request( 54 { url: custLink, method: 'get' }, 55 (err, payload) => resolve(err ? null : payload.data || payload) 56 ) 57 }) 58 59 return { 60 customerEmail: customer.attributes.emails[0].email, 61 customerId: customer.id, 62 } 63 } 64 65 fetchCurrentUserName = async () => { 66 const currentUser = await new Promise((resolve) => { 67 window.Kustomer.request({ url: '/v1/users/current', method: 'get' }, 68 (err, payload) => resolve(err ? null : payload.data || payload) 69 ) 70 }) 71 return currentUser.attributes.name 72 } 73 74 queryStringWithKustomerParams(params) { 75 const searchParams = new URLSearchParams(window.location.search) 76 let merged = { ...params, parentUrl: searchParams.get("parentUrl")} 77 return new URLSearchParams(merged).toString() 78 } 79}
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.