From 4089ba01e0881c89a72332e13bc3a80b6bddec2a Mon Sep 17 00:00:00 2001
From: Jake Vanderwerf <get@jakevanderwerf.ca>
Date: Mon, 29 Jun 2026 22:15:55 +0000
Subject: [PATCH] =DashboardManager overhaul. A bit easier to modify the output of pages. Still have to get the account pages to work as expected, as well as verify the integrations and others are working - but registrar/content pages work as expected. Also fixed up the table generation in CRUD.js and CRUDSkeleton.php

---
 inc/integrations/Square.php |  216 ++++++++++++++++++++++++++++++-----------------------
 1 files changed, 123 insertions(+), 93 deletions(-)

diff --git a/inc/integrations/Square.php b/inc/integrations/Square.php
index ba37b92..d9d4046 100644
--- a/inc/integrations/Square.php
+++ b/inc/integrations/Square.php
@@ -26,6 +26,14 @@
  */
 class Square extends Integrations
 {
+	protected array $allowedContent = [
+		'REGULAR',
+		'FOOD_AND_BEV',
+		'APPOINTMENTS_SERVICE',
+		'DIGITAL',
+		'EVENT',
+		'DONATION'
+	];
 	/**
 	 * Square API Configuration
 	 */
@@ -45,6 +53,9 @@
 	 * OAuth Configuration
 	 */
 	protected bool $isOAuthService = true;
+
+	protected string $orderPostType = '_square_order';
+	protected array $newOrder = [];
 	protected array $oauth = [
 		'authorize' => '',
 		'token' => '',
@@ -80,6 +91,11 @@
 
 		$this->refresh_interval = 7 * DAY_IN_SECONDS;
 
+		$this->newOrder = [
+			'post_type'		=> $this->orderPostType,
+			'post_status' 	=> 'PROPOSED',
+		];
+
 		// Define credential fields
 		$this->fields = [
 			'environment'	=> [
@@ -180,8 +196,7 @@
 				'sync_to_square' => 'Sync Site to Square',
 			]
 		);
-
-		add_action('init', [$this, 'registerSquarePostTypes']);
+		add_action('init', [$this, 'registerSquarePostTypes'], 5);
 	}
 
 	/**
@@ -228,24 +243,20 @@
 					'square_order_id' => [
 						'type' => 'text',
 						'label' => 'Square Order ID',
-						'readonly' => true
 					],
 					'square_payment_id' => [
 						'type' => 'text',
 						'label' => 'Square Payment ID',
-						'readonly' => true
 					],
 					'square_customer_id' => [
 						'type' => 'text',
 						'label' => 'Square Customer ID',
-						'readonly' => true
 					],
 					'amount' => [
 						'type' => 'number',
 						'label' => 'Total Amount (cents)',
-						'readonly' => true
 					],
-					'status' => [
+					'post_status' => [
 						'type' => 'select',
 						'label' => 'Order Status',
 						'options' => [
@@ -255,7 +266,6 @@
 							'COMPLETED' => 'Completed',
 							'CANCELED' => 'Canceled'
 						],
-						'readonly' => true
 					],
 					'fulfillment_status' => [
 						'type' => 'select',
@@ -268,7 +278,6 @@
 							'CANCELED' => 'Canceled',
 							'FAILED' => 'Failed'
 						],
-						'readonly' => true
 					],
 					'pickup_time' => [
 						'type' => 'datetime',
@@ -277,27 +286,22 @@
 					'customer_email' => [
 						'type' => 'email',
 						'label' => 'Customer Email',
-						'readonly' => true
 					],
 					'customer_name' => [
 						'type' => 'text',
 						'label' => 'Customer Name',
-						'readonly' => true
 					],
 					'customer_phone' => [
-						'type' => 'tel',
+						'type' => 'phone',
 						'label' => 'Customer Phone',
-						'readonly' => true
 					],
 					'special_instructions' => [
 						'type' => 'textarea',
 						'label' => 'Special Instructions',
-						'readonly' => true
 					],
 					'items' => [
 						'type' => 'repeater',
 						'label' => 'Order Items',
-						'readonly' => true,
 						'fields' => [
 							'name' => ['type' => 'text', 'label' => 'Item Name'],
 							'quantity' => ['type' => 'number', 'label' => 'Quantity'],
@@ -308,35 +312,30 @@
 					'receipt_url' => [
 						'type' => 'url',
 						'label' => 'Receipt URL',
-						'readonly' => true
 					],
 					'created_at' => [
 						'type' => 'datetime',
 						'label' => 'Created At',
-						'readonly' => true
 					],
 					'updated_at' => [
 						'type' => 'datetime',
 						'label' => 'Last Updated',
-						'readonly' => true
 					]
 				];
 	}
 
 	public function registerSquarePostTypes():void
 	{
-		$orders = Registrar::forPost('_sq_orders', 'Square Order', 'Square Orders');
+		$orders = Registrar::forPost($this->orderPostType, 'Square Order', 'Square Orders');
 		$orders->make([
-			'public'	=> false
-			]
-		);
+			'public'	=> true
+		]);
 		$orders->setAll(['system']);
 
 		$fields = $orders->fields();
 		foreach ($this->getOrderFields() as $fieldName => $config) {
 			$fields->addField($fieldName, $config);
 		}
-
 	}
 
 	/**
@@ -770,7 +769,7 @@
 						'name' => $variation['name'],
 						'pricing_type' => 'FIXED_PRICING',
 						'price_money' => [
-							'amount' => intval($variation['price'] * 100), // Convert to cents
+							'amount' => intval($variation['_square_price'] * 100), // Convert to cents
 							'currency' => 'USD'
 						]
 					]
@@ -785,7 +784,7 @@
 					'name' => 'Regular',
 					'pricing_type' => 'FIXED_PRICING',
 					'price_money' => [
-						'amount' => intval(($itemData['price'] ?? 0) * 100),
+						'amount' => intval(($itemData['_square_price'] ?? 0) * 100),
 						'currency' => 'USD'
 					]
 				]
@@ -843,12 +842,10 @@
 		}
 
 		add_action('wp_login', [$this, 'trackUserLogin'], 10, 2);
-		add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);
+        add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);
 
-		// Shared checkout UI (replaces outputCheckout)
 		add_filter('jvbAdditionalActions', [Checkout::class, 'render']);
 
-		// Square-specific checkout description
 		add_filter('jvb_checkout_description', function (string $desc, string $provider) {
 			if ($provider === 'square') {
 				return 'Securely checkout with your name, email, and payments processed by Square.';
@@ -866,9 +863,8 @@
 		add_filter('jvb_checkout_browse_text', function () {
 			return 'browse our menu';
 		});
-
 		// Register queue executor types
-		$this->registerQueueTypes();
+		add_action('init', [$this, 'registerQueueTypes'], 10);
 	}
 
 	/**
@@ -897,36 +893,36 @@
 			]);
 	}
 
-	protected function registerQueueTypes(): void
+	public function registerQueueTypes(): void
 	{
 		$queue    = JVB()->queue();
 		$executor = new IntegrationExecutor();
 
-		$queue->registry()->register('square_sync_to', new TypeConfig(
+		$queue->registry()->register(self::$syncTo, new TypeConfig(
 			executor:   $executor,
 			chunkKey:   'items',
 			chunkSize:  50,
 			maxRetries: 3
 		));
 
-		$queue->registry()->register('square_delete_from', new TypeConfig(
+		$queue->registry()->register(self::$deleteFrom, new TypeConfig(
 			executor:   $executor,
 			chunkKey:   'external_ids',
 			chunkSize:  200,
 			maxRetries: 2
 		));
 
-		$queue->registry()->register('square_sync_from', new TypeConfig(
+		$queue->registry()->register(self::$syncFrom, new TypeConfig(
 			executor:   $executor,
 			maxRetries: 3
 		));
 
-		$queue->registry()->register('square_sync_customer', new TypeConfig(
+		$queue->registry()->register(self::$syncCustomer, new TypeConfig(
 			executor:   $executor,
 			maxRetries: 2
 		));
 
-		$queue->registry()->register('square_import', new TypeConfig(
+		$queue->registry()->register(self::$import, new TypeConfig(
 			executor:   $executor,
 			maxRetries: 3
 		));
@@ -941,7 +937,7 @@
 	 */
 	protected function handleTheSavePost(int $postID, \WP_Post $post, bool $update, array $settings): void
 	{
-		$this->queueOperation('sync_to', [
+		$this->queueOperation(self::$syncTo, [
 			'items'   => [$postID],
 			'user_id' => $this->userID,
 		], [
@@ -960,7 +956,7 @@
 		$square_id = get_post_meta($postID, BASE . '_square_catalog_id', true);
 
 		if ($square_id) {
-			$this->queueOperation('delete_from', [
+			$this->queueOperation(self::$deleteFrom, [
 				'external_ids' => [$square_id],
 				'post_id'      => $postID,
 			], [
@@ -970,26 +966,6 @@
 	}
 
 	/**
-	 * @deprecated IntegrationExecutor handles new operations via registerQueueTypes().
-	 * Kept for legacy-typed operations ('square_sync_to_square') already queued.
-	 * Safe to remove once all legacy operations have been processed.
-	 */
-	public function processOperation(WP_Error|array $result, object $operation, array $data): WP_Error|array
-	{
-		$base   = strtolower($this->service_name) . '_';
-		$square = array_key_exists('user', $data) ? new self((int) $data['user']) : $this;
-
-		return match ($operation->type) {
-			$base . 'sync_to_square'     => $square->processSyncToSquare($data),
-			$base . 'delete_from_square' => $square->processDeleteFromSquare($data),
-			$base . 'sync_from_square'   => $square->processSyncFromSquare($data),
-			$base . 'sync_customer'      => $square->processSyncCustomer($data),
-			default                      => $result,
-		};
-	}
-
-
-	/**
 	 * Process sync to Square
 	 */
 	private function processSyncToSquare(array $data): array
@@ -1296,7 +1272,7 @@
 		if (!empty($product_variations) && is_array($product_variations)) {
 			foreach ($product_variations as $index => $variation_data) {
 				// Skip empty variations
-				if (empty($variation_data['name']) && empty($variation_data['sku'])) {
+				if (empty($variation_data['name']) && empty($variation_data['_square_sku'])) {
 					continue;
 				}
 
@@ -1328,7 +1304,7 @@
 								break;
 
 							case 'sku':
-								$variation['item_variation_data']['sku'] = $variation_data[$wp_field];
+								$variation['item_variation_data']['_square_sku'] = $variation_data[$wp_field];
 								break;
 
 							case 'track_inventory':
@@ -1389,15 +1365,15 @@
 
 		$defaults = [
 			'name' => 'name',
-			'id' => '_square_catalog_id',
-			'sku' => 'sku',
-			'price' => 'price',
-			'track_inventory' => 'track_inventory',
-			'service_duration' => 'service_duration',
-			'available_for_booking' => 'available_for_booking',
-			'gift_card_type' => 'gift_card_type',
-			'ingredients' => 'ingredients',
-			'preparation_time_duration' => 'preparation_time_duration'
+			'id' => '_square_item_id',
+			'sku' => '_square_sku',
+			'price' => '_square_price',
+			'track_inventory' => '_square_track_inventory',
+			'service_duration' => '_square_service_duration',
+			'available_for_booking' => '_square_available_for_booking',
+			'gift_card_type' => '_square_gift_card_type',
+			'ingredients' => '_square_ingredients',
+			'preparation_time_duration' => '_square_preparation_time_duration'
 		];
 
 		$extended = apply_filters(
@@ -1466,15 +1442,15 @@
 			'description_html' => 'post_content',
 			'abbreviation' => 'abbreviation',
 			'id' => '_square_catalog_id',
-			'sku' => 'sku',
+			'sku' => '_square_sku',
 			'category_id' => 'category',
 			'image_ids' => 'post_thumbnail',
-			'price' => 'price',
+			'price' => '_square_price',
 			'tax_ids' => 'tax_ids',
 			// Availability
-			'available_online' => 'available_online',
-			'available_for_pickup' => 'available_for_pickup',
-			'available_electronically' => 'available_electronically',
+			'available_online' => '_square_available_online',
+			'available_for_pickup' => '_square_available_for_pickup',
+			'available_electronically' => '_square_available_electronically',
 			// Modifiers
 			'modifier_list_info' => 'modifiers',
 			// Item options
@@ -1965,6 +1941,7 @@
 	 */
 	public function enqueueScripts(): void
 	{
+		jvbInlineStyles('forms');
 		$this->loadCredentials();
 		$sdk_url = $this->environment === 'production'
 			? 'https://web.squarecdn.com/v1/square.js'
@@ -1982,8 +1959,8 @@
 		wp_register_script(
 			'jvb-checkout',
 			JVB_URL . 'assets/js/min/checkout.min.js',
-			['jvb-utility', 'jvb-queue', 'jvb-a11y', 'jvb-cache', 'jvb-tabs', 'jvb-popup'],
-			'1.1.31',
+			['jvb-utility', 'jvb-queue', 'jvb-a11y', 'jvb-cache', 'jvb-tabs', 'jvb-popup', 'jvb-login'],
+			'1.1.32',
 			['strategy' => 'defer', 'in_footer' => true]
 		);
 
@@ -1992,19 +1969,17 @@
 			'jvb-square-checkout',
 			JVB_URL . 'assets/js/min/square.min.js',
 			['jvb-checkout', 'square-payments-sdk'],
-			'1.1.31',
+			'1.1.32',
 			['strategy' => 'defer', 'in_footer' => true]
 		);
 
 		wp_enqueue_script('jvb-square-checkout');
 
 		wp_localize_script('jvb-square-checkout', 'squareConfig', [
-//TODO			'isOpen'         => jvbIsOpen(),
+			'isOpen'         => jvbIsOpen()?'1':'0',
 			'application_id' => $this->credentials['client_id'] ?? '',
 			'location_id'    => $this->locationId,
 			'environment'    => $this->environment,
-			'api_url'        => rest_url('jvb/v1/square/'),
-			'nonce'          => wp_create_nonce('wp_rest'),
 			'currency'       => get_option(BASE . 'currency', 'CAD'),
 			'is_logged_in'   => is_user_logged_in(),
 			'user_email'     => is_user_logged_in() ? wp_get_current_user()->user_email : '',
@@ -2312,7 +2287,7 @@
 			foreach ($item['item_data']['variations'] as $index => $variation) {
 				$var_data = [
 					'name' => $variation['item_variation_data']['name'] ?? '',
-					'sku' => $variation['item_variation_data']['sku'] ?? '',
+					'sku' => $variation['item_variation_data']['_square_sku'] ?? '',
 				];
 
 				// Extract price
@@ -2753,10 +2728,13 @@
 		];
 	}
 	public function getAdditionalFields(?string $content_type = null):array {
+		if ($content_type === 'customer') {
+			return $this->getCustomerFields();
+		}
 		if ($content_type && array_key_exists($content_type, $this->contentTypes)){
 			$array = $this->contentTypes[$content_type];
 			return array_combine(
-				array_map(fn($k) => 'sq_' . $k, array_keys($array)),
+				array_map(fn($k) => '_square_' . $k, array_keys($array)),
 				$array
 			);
 		} else if ($content_type && !array_key_exists($content_type, $this->contentTypes)) {
@@ -2764,17 +2742,62 @@
 			return [];
 		}
 		$array = $this->setBaseFields();
-		return array_combine(
-			array_map(fn($k) => 'sq_' . $k, array_keys($array)),
-			$array
-		);
+        return array_combine(
+            array_map(fn($k) => '_square_' . $k, array_keys($array)),
+            $array
+        );
+	}
+
+	protected function getCustomerFields():array
+	{
+		return [
+			'customer_id'	=> [
+				'type'	=> 'text',
+				'label'	=> 'Square Customer ID',
+				'hidden'=> true,
+			],
+			'address_line_1'	=> [
+				'type'	=> 'text',
+				'label'	=> 'Address Line 1',
+				'hint'	=> 'ex: 6551 111 St NW',
+				'required'	=> true,
+				'section'	=> 'about'
+			],
+			'address_line_2'	=> [
+				'type'	=> 'text',
+				'label'	=> 'Address Line 2',
+				'hint'	=> 'ex: Unit 2',
+				'section'	=> 'about'
+			],
+			'city'	=> [
+				'type'	=> 'text',
+				'label'=> 'City',
+				'section'	=> 'about',
+				'required'	=> true,
+			],
+			'state' => [
+				'type'	=> 'text',
+				'label' => 'Province',
+				'hint' => 'The two-character code, example: AB',
+				'default'=> 'AB',
+				'section'	=> 'about',
+				'required'	=> true,
+			],
+			'countryCode'	=> [
+				'type'	=> 'text',
+				'label'	=> 'Country Code',
+				'hint'	=> 'The tw-character country code, example: CA',
+				'default'	=> 'CA',
+				'section'	=> 'about',
+				'required'	=> true,
+			]
+		];
 	}
 	protected function setBaseFields():array
 	{
 		return [
 			'price' => [
 				'type'        => 'number',
-				'bulkEdit'    => true,
 				'label'       => 'Price',
 				'step'        => 0.01,
 				'max'         => 99999,
@@ -2819,6 +2842,11 @@
 				'label'       => 'Variation Name',
 				'description' => 'e.g., "Small", "Large", "Red", etc.'
 			],
+            'sku' => [
+                'type'        => 'text',
+                'label'       => 'SKU',
+                'description' => 'Stock keeping unit'
+            ],
 			'price' => [
 				'type'        => 'number',
 				'label'       => 'Price',
@@ -2826,18 +2854,17 @@
 				'max'         => 99999,
 				'description' => 'Price for this variation'
 			],
-
 			'track_inventory'	=> [
 				'type'	=> 'true_false',
 				'label'	=> 'Track Inventory',
 			],
-			'_square_item_id' => [
+			'item_id' => [
 				'type'        => 'text',
 				'label'       => 'Square Variation ID',
 				'description' => 'Square catalog ID for this variation',
 				'hidden'      => true
 			],
-			'_square_last_sync' => [
+			'last_sync' => [
 				'type'   => 'datetime',
 				'label'  => 'Last Sync',
 				'hidden' => true
@@ -2878,7 +2905,10 @@
 				];
 				break;
 		}
-		return $fields;
+		return array_combine(
+            array_map(fn($k) => '_square_' . $k, array_keys($fields)),
+            $fields
+        );
 	}
 	protected function setFoodAndBevFields():array
 	{
@@ -3362,7 +3392,7 @@
 				// Ad-hoc line item (not recommended - no tax/inventory automation)
 				$line_item['name'] = $item['name'];
 				$line_item['base_price_money'] = [
-					'amount' => (int)$item['price'],
+					'amount' => (int)$item['_square_price'],
 					'currency' => $this->getCurrency()
 				];
 			}
@@ -3454,7 +3484,7 @@
 
 		// Create order post
 		$order_post_id = wp_insert_post([
-			'post_type' => BASE . '_sq_orders',
+			'post_type' => BASE . '_square_orders',
 			'post_title' => 'Order #' . $order_data['square_order_id'],
 			'post_status' => 'publish',
 			'post_author' => $user_id // Associate with user if logged in

--
Gitblit v1.10.0