AUDIENCE_ADDAUSER::get_samples_js()


Source

File: src/integrations/mailchimp/actions/audience-addauser.php

	public function get_samples_js() {
		// Start output
		ob_start();
		// It's optional to add the <script> tags
		// This must have only one anonymous function
		?>
		<script>
			// Do when the user clicks on send test
			function ($button, data, modules) {
				// Create a configuration object
				let config = {
					// In milliseconds, the time between each call
					timeBetweenCalls: 1 * 1000,
					// In milliseconds, the time we're going to check for samples
					checkingTime: 60 * 1000,
					// Links
					links: {
						noResultsSupport: 'https://automatorplugin.com/knowledge-base/google-sheets/'
					},
					// i18n
					i18n: {
						checkingHooks: "<?php printf( __( "We're checking for columns. We'll keep trying for %s seconds.", 'uncanny-automator' ), '{{time}}' ); ?>",
						noResultsTrouble: "<?php _e( 'We had trouble finding columns.', 'uncanny-automator' ); ?>",
						noResultsSupport: "<?php _e( 'See more details or get help', 'uncanny-automator' ); ?>",
						samplesModalTitle: "<?php _e( "Here is the data we've collected", 'uncanny-automator' ); ?>",
						samplesModalWarning: "<?php /* translators: 1. Button */ printf( __( 'Clicking on \"%1$s\" will remove your current fields and will use the ones on the table above instead.', 'uncanny-automator' ), '{{confirmButton}}' ); ?>",
						samplesTableValueType: "<?php _e( 'Value type', 'uncanny-automator' ); ?>",
						samplesTableReceivedData: "<?php _e( 'Received data', 'uncanny-automator' ); ?>",
						samplesModalButtonConfirm: "<?php /* translators: Non-personal infinitive verb */ _e( 'Use these fields', 'uncanny-automator' ); ?>",
						samplesModalButtonCancel: "<?php /* translators: Non-personal infinitive verb */ _e( 'Do nothing', 'uncanny-automator' ); ?>",
					}
				}
				// Create the variable we're going to use to know if we have to keep doing calls
				let foundResults = false
				// Get the date when this function started
				let startDate = new Date()
				// Create array with the data we're going to send
				let dataToBeSent = {
					action: 'get_mailchimp_audience_fields',
					nonce: UncannyAutomator.nonce,
					recipe_id: UncannyAutomator.recipe.id,
					item_id: data.item.id,
					audience: data.values.MCLIST
				}
				// Add notice to the item
				// Create notice
				let $notice = jQuery('<div/>', {
					'class': 'item-options__notice item-options__notice--warning'
				})
				// Add notice message
				$notice.html(config.i18n.checkingHooks.replace('{{time}}', parseInt(config.checkingTime / 1000)))
				// Get the notices container
				let $noticesContainer = jQuery('.item[data-id="' + data.item.id + '"] .item-options__notices')
				// Add notice
				$noticesContainer.html($notice)
				// Create the function we're going to use recursively to
				// do check for the samples
				var getSamples = function () {
					// Do AJAX call
					jQuery.ajax({
						method: 'POST',
						dataType: 'json',
						url: ajaxurl,
						data: dataToBeSent,
						// Set the checking time as the timeout
						timeout: config.checkingTime,
						success: function (response) {
							// Get new date
							let currentDate = new Date()
							// Define the default value of foundResults
							let foundResults = false
							// Check if the response was successful
							if (response.success) {
								// Check if we got the rows from a sample
								if (response.samples.length > 0) {
									// Update foundResults
									foundResults = true
								}
							}
							// Check if we have to do another call
							let shouldDoAnotherCall = false
							// First, check if we don't have results
							if (!foundResults) {
								// Check if we still have time left
								if ((currentDate.getTime() - startDate.getTime()) <= config.checkingTime) {
									// Update result
									shouldDoAnotherCall = true
								}
							}
							if (shouldDoAnotherCall) {
								// Wait and do another call
								setTimeout(function () {
									// Invoke this function again
									getSamples()
								}, config.timeBetweenCalls)
							} else {
								// Add loading animation to the button
								$button.removeClass('uap-btn--loading uap-btn--disabled')
								// Iterate samples and create an array with the rows
								let rows = []
								let keys = {}
								jQuery.each(response.samples, function (index, sample) {
									// Iterate keys
									jQuery.each(sample, function (index, row) {
										// Check if the we already added this key
										if (typeof keys[row.key] !== 'undefined') {
											// Then just append the value
											// rows[ keys[ row.key ] ].data = rows[ keys[ row.key ] ].data + ', ' + row.data;
										} else {
											// Add row and save the index
											keys[row.key] = rows.push(row)
										}
									})
								})
								// Get the field with the fields (WEBHOOK_DATA)
								let mergeFields = data.item.options.AUDIENCEADDAUSER.fields[6]
								// Remove all the current fields
								mergeFields.fieldRows = []
								// Add new rows. Iterate rows from the sample
								jQuery.each(rows, function (index, row) {
									// Add row
									mergeFields.addRow({
										FIELD_NAME: row.key
									}, false)
								})
								// Render again
								mergeFields.reRender()
								// Check if it has results
								if (foundResults) {
									// Remove notice
									$notice.remove()
								} else {
									// Change the notice type
									$notice.removeClass('item-options__notice--warning').addClass('item-options__notice--error')
									// Create a new notice message
									let noticeMessage = config.i18n.noResultsTrouble
									// Change the notice message
									$notice.html(noticeMessage + ' ')
									// Add help link
									let $noticeHelpLink = jQuery('<a/>', {
										target: '_blank',
										href: config.links.noResultsSupport
									}).text(config.i18n.noResultsSupport)
									$notice.append($noticeHelpLink)
								}
							}
						},
						statusCode: {
							403: function () {
								location.reload()
							}
						},
						fail: function (response) {
						}
					})
				}
				// Add loading animation to the button
				$button.addClass('uap-btn--loading uap-btn--disabled')
				// Try to get samples
				getSamples()
			}
		</script>
		<?php
		// Get output
		$output = ob_get_clean();
		// Return output
		return $output;
	}