quickbooks-medusa-plugin 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1831 +1,5 @@
1
- import { jsx, jsxs } from "react/jsx-runtime";
2
- import { defineRouteConfig } from "@medusajs/admin-sdk";
3
- import { toast, Text, Container, Heading, Badge, Button, Label, Input, Switch } from "@medusajs/ui";
4
- import React, { useState, useEffect } from "react";
5
- var isCheckBoxInput = (element) => element.type === "checkbox";
6
- var isDateObject = (value) => value instanceof Date;
7
- var isNullOrUndefined = (value) => value == null;
8
- const isObjectType = (value) => typeof value === "object";
9
- var isObject = (value) => !isNullOrUndefined(value) && !Array.isArray(value) && isObjectType(value) && !isDateObject(value);
10
- var getEventValue = (event) => isObject(event) && event.target ? isCheckBoxInput(event.target) ? event.target.checked : event.target.value : event;
11
- var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
12
- var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
13
- var isPlainObject = (tempObject) => {
14
- const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
15
- return isObject(prototypeCopy) && prototypeCopy.hasOwnProperty("isPrototypeOf");
16
- };
17
- var isWeb = typeof window !== "undefined" && typeof window.HTMLElement !== "undefined" && typeof document !== "undefined";
18
- function cloneObject(data) {
19
- let copy;
20
- const isArray = Array.isArray(data);
21
- if (data instanceof Date) {
22
- copy = new Date(data);
23
- } else if (data instanceof Set) {
24
- copy = new Set(data);
25
- } else if (!(isWeb && (data instanceof Blob || data instanceof FileList)) && (isArray || isObject(data))) {
26
- copy = isArray ? [] : {};
27
- if (!isArray && !isPlainObject(data)) {
28
- copy = data;
29
- } else {
30
- for (const key in data) {
31
- if (data.hasOwnProperty(key)) {
32
- copy[key] = cloneObject(data[key]);
33
- }
34
- }
35
- }
36
- } else {
37
- return data;
38
- }
39
- return copy;
40
- }
41
- var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
42
- var isUndefined = (val) => val === void 0;
43
- var get = (object, path, defaultValue) => {
44
- if (!path || !isObject(object)) {
45
- return defaultValue;
46
- }
47
- const result = compact(path.split(/[,[\].]+?/)).reduce((result2, key) => isNullOrUndefined(result2) ? result2 : result2[key], object);
48
- return isUndefined(result) || result === object ? isUndefined(object[path]) ? defaultValue : object[path] : result;
49
- };
50
- var isBoolean = (value) => typeof value === "boolean";
51
- const EVENTS = {
52
- BLUR: "blur",
53
- FOCUS_OUT: "focusout",
54
- CHANGE: "change"
55
- };
56
- const VALIDATION_MODE = {
57
- onBlur: "onBlur",
58
- onChange: "onChange",
59
- onSubmit: "onSubmit",
60
- onTouched: "onTouched",
61
- all: "all"
62
- };
63
- const INPUT_VALIDATION_RULES = {
64
- max: "max",
65
- min: "min",
66
- maxLength: "maxLength",
67
- minLength: "minLength",
68
- pattern: "pattern",
69
- required: "required",
70
- validate: "validate"
71
- };
72
- const HookFormContext = React.createContext(null);
73
- const useFormContext = () => React.useContext(HookFormContext);
74
- var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
75
- const result = {
76
- defaultValues: control._defaultValues
77
- };
78
- for (const key in formState) {
79
- Object.defineProperty(result, key, {
80
- get: () => {
81
- const _key = key;
82
- if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
83
- control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
84
- }
85
- localProxyFormState && (localProxyFormState[_key] = true);
86
- return formState[_key];
87
- }
88
- });
89
- }
90
- return result;
91
- };
92
- var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
93
- var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
94
- updateFormState(formStateData);
95
- const { name, ...formState } = formStateData;
96
- return isEmptyObject(formState) || Object.keys(formState).length >= Object.keys(_proxyFormState).length || Object.keys(formState).find((key) => _proxyFormState[key] === (!isRoot || VALIDATION_MODE.all));
97
- };
98
- var convertToArrayPayload = (value) => Array.isArray(value) ? value : [value];
99
- var shouldSubscribeByName = (name, signalName, exact) => !name || !signalName || name === signalName || convertToArrayPayload(name).some((currentName) => currentName && (exact ? currentName === signalName : currentName.startsWith(signalName) || signalName.startsWith(currentName)));
100
- function useSubscribe(props) {
101
- const _props = React.useRef(props);
102
- _props.current = props;
103
- React.useEffect(() => {
104
- const subscription = !props.disabled && _props.current.subject && _props.current.subject.subscribe({
105
- next: _props.current.next
106
- });
107
- return () => {
108
- subscription && subscription.unsubscribe();
109
- };
110
- }, [props.disabled]);
111
- }
112
- function useFormState(props) {
113
- const methods = useFormContext();
114
- const { control = methods.control, disabled, name, exact } = props;
115
- const [formState, updateFormState] = React.useState(control._formState);
116
- const _mounted = React.useRef(true);
117
- const _localProxyFormState = React.useRef({
118
- isDirty: false,
119
- isLoading: false,
120
- dirtyFields: false,
121
- touchedFields: false,
122
- isValidating: false,
123
- isValid: false,
124
- errors: false
125
- });
126
- const _name = React.useRef(name);
127
- _name.current = name;
128
- useSubscribe({
129
- disabled,
130
- next: (value) => _mounted.current && shouldSubscribeByName(_name.current, value.name, exact) && shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) && updateFormState({
131
- ...control._formState,
132
- ...value
133
- }),
134
- subject: control._subjects.state
135
- });
136
- React.useEffect(() => {
137
- _mounted.current = true;
138
- _localProxyFormState.current.isValid && control._updateValid(true);
139
- return () => {
140
- _mounted.current = false;
141
- };
142
- }, [control]);
143
- return getProxyFormState(formState, control, _localProxyFormState.current, false);
144
- }
145
- var isString = (value) => typeof value === "string";
146
- var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
147
- if (isString(names)) {
148
- isGlobal && _names.watch.add(names);
149
- return get(formValues, names, defaultValue);
150
- }
151
- if (Array.isArray(names)) {
152
- return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
153
- }
154
- isGlobal && (_names.watchAll = true);
155
- return formValues;
156
- };
157
- function useWatch(props) {
158
- const methods = useFormContext();
159
- const { control = methods.control, name, defaultValue, disabled, exact } = props;
160
- const _name = React.useRef(name);
161
- _name.current = name;
162
- useSubscribe({
163
- disabled,
164
- subject: control._subjects.values,
165
- next: (formState) => {
166
- if (shouldSubscribeByName(_name.current, formState.name, exact)) {
167
- updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
168
- }
169
- }
170
- });
171
- const [value, updateValue] = React.useState(control._getWatch(name, defaultValue));
172
- React.useEffect(() => control._removeUnmounted());
173
- return value;
174
- }
175
- var isKey = (value) => /^\w*$/.test(value);
176
- var stringToPath = (input) => compact(input.replace(/["|']|\]/g, "").split(/\.|\[/));
177
- var set = (object, path, value) => {
178
- let index = -1;
179
- const tempPath = isKey(path) ? [path] : stringToPath(path);
180
- const length = tempPath.length;
181
- const lastIndex = length - 1;
182
- while (++index < length) {
183
- const key = tempPath[index];
184
- let newValue = value;
185
- if (index !== lastIndex) {
186
- const objValue = object[key];
187
- newValue = isObject(objValue) || Array.isArray(objValue) ? objValue : !isNaN(+tempPath[index + 1]) ? [] : {};
188
- }
189
- object[key] = newValue;
190
- object = object[key];
191
- }
192
- return object;
193
- };
194
- function useController(props) {
195
- const methods = useFormContext();
196
- const { name, disabled, control = methods.control, shouldUnregister } = props;
197
- const isArrayField = isNameInFieldArray(control._names.array, name);
198
- const value = useWatch({
199
- control,
200
- name,
201
- defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
202
- exact: true
203
- });
204
- const formState = useFormState({
205
- control,
206
- name
207
- });
208
- const _registerProps = React.useRef(control.register(name, {
209
- ...props.rules,
210
- value,
211
- ...isBoolean(props.disabled) ? { disabled: props.disabled } : {}
212
- }));
213
- React.useEffect(() => {
214
- const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
215
- const updateMounted = (name2, value2) => {
216
- const field = get(control._fields, name2);
217
- if (field) {
218
- field._f.mount = value2;
219
- }
220
- };
221
- updateMounted(name, true);
222
- if (_shouldUnregisterField) {
223
- const value2 = cloneObject(get(control._options.defaultValues, name));
224
- set(control._defaultValues, name, value2);
225
- if (isUndefined(get(control._formValues, name))) {
226
- set(control._formValues, name, value2);
227
- }
228
- }
229
- return () => {
230
- (isArrayField ? _shouldUnregisterField && !control._state.action : _shouldUnregisterField) ? control.unregister(name) : updateMounted(name, false);
231
- };
232
- }, [name, control, isArrayField, shouldUnregister]);
233
- React.useEffect(() => {
234
- if (get(control._fields, name)) {
235
- control._updateDisabledField({
236
- disabled,
237
- fields: control._fields,
238
- name,
239
- value: get(control._fields, name)._f.value
240
- });
241
- }
242
- }, [disabled, name, control]);
243
- return {
244
- field: {
245
- name,
246
- value,
247
- ...isBoolean(disabled) || isBoolean(formState.disabled) ? { disabled: formState.disabled || disabled } : {},
248
- onChange: React.useCallback((event) => _registerProps.current.onChange({
249
- target: {
250
- value: getEventValue(event),
251
- name
252
- },
253
- type: EVENTS.CHANGE
254
- }), [name]),
255
- onBlur: React.useCallback(() => _registerProps.current.onBlur({
256
- target: {
257
- value: get(control._formValues, name),
258
- name
259
- },
260
- type: EVENTS.BLUR
261
- }), [name, control]),
262
- ref: (elm) => {
263
- const field = get(control._fields, name);
264
- if (field && elm) {
265
- field._f.ref = {
266
- focus: () => elm.focus(),
267
- select: () => elm.select(),
268
- setCustomValidity: (message) => elm.setCustomValidity(message),
269
- reportValidity: () => elm.reportValidity()
270
- };
271
- }
272
- }
273
- },
274
- formState,
275
- fieldState: Object.defineProperties({}, {
276
- invalid: {
277
- enumerable: true,
278
- get: () => !!get(formState.errors, name)
279
- },
280
- isDirty: {
281
- enumerable: true,
282
- get: () => !!get(formState.dirtyFields, name)
283
- },
284
- isTouched: {
285
- enumerable: true,
286
- get: () => !!get(formState.touchedFields, name)
287
- },
288
- error: {
289
- enumerable: true,
290
- get: () => get(formState.errors, name)
291
- }
292
- })
293
- };
294
- }
295
- const Controller = (props) => props.render(useController(props));
296
- var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria ? {
297
- ...errors[name],
298
- types: {
299
- ...errors[name] && errors[name].types ? errors[name].types : {},
300
- [type]: message || true
301
- }
302
- } : {};
303
- var getValidationModes = (mode) => ({
304
- isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
305
- isOnBlur: mode === VALIDATION_MODE.onBlur,
306
- isOnChange: mode === VALIDATION_MODE.onChange,
307
- isOnAll: mode === VALIDATION_MODE.all,
308
- isOnTouch: mode === VALIDATION_MODE.onTouched
309
- });
310
- var isWatched = (name, _names, isBlurEvent) => !isBlurEvent && (_names.watchAll || _names.watch.has(name) || [..._names.watch].some((watchName) => name.startsWith(watchName) && /^\.\w+/.test(name.slice(watchName.length))));
311
- const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
312
- for (const key of fieldsNames || Object.keys(fields)) {
313
- const field = get(fields, key);
314
- if (field) {
315
- const { _f, ...currentField } = field;
316
- if (_f) {
317
- if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {
318
- break;
319
- } else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {
320
- break;
321
- } else {
322
- iterateFieldsByAction(currentField, action);
323
- }
324
- } else if (isObject(currentField)) {
325
- iterateFieldsByAction(currentField, action);
326
- }
327
- }
328
- }
329
- };
330
- var updateFieldArrayRootError = (errors, error, name) => {
331
- const fieldArrayErrors = compact(get(errors, name));
332
- set(fieldArrayErrors, "root", error[name]);
333
- set(errors, name, fieldArrayErrors);
334
- return errors;
335
- };
336
- var isFileInput = (element) => element.type === "file";
337
- var isFunction = (value) => typeof value === "function";
338
- var isHTMLElement = (value) => {
339
- if (!isWeb) {
340
- return false;
341
- }
342
- const owner = value ? value.ownerDocument : 0;
343
- return value instanceof (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement);
344
- };
345
- var isMessage = (value) => isString(value);
346
- var isRadioInput = (element) => element.type === "radio";
347
- var isRegex = (value) => value instanceof RegExp;
348
- const defaultResult = {
349
- value: false,
350
- isValid: false
351
- };
352
- const validResult = { value: true, isValid: true };
353
- var getCheckboxValue = (options) => {
354
- if (Array.isArray(options)) {
355
- if (options.length > 1) {
356
- const values = options.filter((option) => option && option.checked && !option.disabled).map((option) => option.value);
357
- return { value: values, isValid: !!values.length };
358
- }
359
- return options[0].checked && !options[0].disabled ? (
360
- // @ts-expect-error expected to work in the browser
361
- options[0].attributes && !isUndefined(options[0].attributes.value) ? isUndefined(options[0].value) || options[0].value === "" ? validResult : { value: options[0].value, isValid: true } : validResult
362
- ) : defaultResult;
363
- }
364
- return defaultResult;
365
- };
366
- const defaultReturn = {
367
- isValid: false,
368
- value: null
369
- };
370
- var getRadioValue = (options) => Array.isArray(options) ? options.reduce((previous, option) => option && option.checked && !option.disabled ? {
371
- isValid: true,
372
- value: option.value
373
- } : previous, defaultReturn) : defaultReturn;
374
- function getValidateError(result, ref, type = "validate") {
375
- if (isMessage(result) || Array.isArray(result) && result.every(isMessage) || isBoolean(result) && !result) {
376
- return {
377
- type,
378
- message: isMessage(result) ? result : "",
379
- ref
380
- };
381
- }
382
- }
383
- var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData) ? validationData : {
384
- value: validationData,
385
- message: ""
386
- };
387
- var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
388
- const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled } = field._f;
389
- const inputValue = get(formValues, name);
390
- if (!mount || disabled) {
391
- return {};
392
- }
393
- const inputRef = refs ? refs[0] : ref;
394
- const setCustomValidity = (message) => {
395
- if (shouldUseNativeValidation && inputRef.reportValidity) {
396
- inputRef.setCustomValidity(isBoolean(message) ? "" : message || "");
397
- inputRef.reportValidity();
398
- }
399
- };
400
- const error = {};
401
- const isRadio = isRadioInput(ref);
402
- const isCheckBox = isCheckBoxInput(ref);
403
- const isRadioOrCheckbox2 = isRadio || isCheckBox;
404
- const isEmpty = (valueAsNumber || isFileInput(ref)) && isUndefined(ref.value) && isUndefined(inputValue) || isHTMLElement(ref) && ref.value === "" || inputValue === "" || Array.isArray(inputValue) && !inputValue.length;
405
- const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
406
- const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
407
- const message = exceedMax ? maxLengthMessage : minLengthMessage;
408
- error[name] = {
409
- type: exceedMax ? maxType : minType,
410
- message,
411
- ref,
412
- ...appendErrorsCurry(exceedMax ? maxType : minType, message)
413
- };
414
- };
415
- if (isFieldArray ? !Array.isArray(inputValue) || !inputValue.length : required && (!isRadioOrCheckbox2 && (isEmpty || isNullOrUndefined(inputValue)) || isBoolean(inputValue) && !inputValue || isCheckBox && !getCheckboxValue(refs).isValid || isRadio && !getRadioValue(refs).isValid)) {
416
- const { value, message } = isMessage(required) ? { value: !!required, message: required } : getValueAndMessage(required);
417
- if (value) {
418
- error[name] = {
419
- type: INPUT_VALIDATION_RULES.required,
420
- message,
421
- ref: inputRef,
422
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message)
423
- };
424
- if (!validateAllFieldCriteria) {
425
- setCustomValidity(message);
426
- return error;
427
- }
428
- }
429
- }
430
- if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
431
- let exceedMax;
432
- let exceedMin;
433
- const maxOutput = getValueAndMessage(max);
434
- const minOutput = getValueAndMessage(min);
435
- if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
436
- const valueNumber = ref.valueAsNumber || (inputValue ? +inputValue : inputValue);
437
- if (!isNullOrUndefined(maxOutput.value)) {
438
- exceedMax = valueNumber > maxOutput.value;
439
- }
440
- if (!isNullOrUndefined(minOutput.value)) {
441
- exceedMin = valueNumber < minOutput.value;
442
- }
443
- } else {
444
- const valueDate = ref.valueAsDate || new Date(inputValue);
445
- const convertTimeToDate = (time) => /* @__PURE__ */ new Date((/* @__PURE__ */ new Date()).toDateString() + " " + time);
446
- const isTime = ref.type == "time";
447
- const isWeek = ref.type == "week";
448
- if (isString(maxOutput.value) && inputValue) {
449
- exceedMax = isTime ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value) : isWeek ? inputValue > maxOutput.value : valueDate > new Date(maxOutput.value);
450
- }
451
- if (isString(minOutput.value) && inputValue) {
452
- exceedMin = isTime ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value) : isWeek ? inputValue < minOutput.value : valueDate < new Date(minOutput.value);
453
- }
454
- }
455
- if (exceedMax || exceedMin) {
456
- getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
457
- if (!validateAllFieldCriteria) {
458
- setCustomValidity(error[name].message);
459
- return error;
460
- }
461
- }
462
- }
463
- if ((maxLength || minLength) && !isEmpty && (isString(inputValue) || isFieldArray && Array.isArray(inputValue))) {
464
- const maxLengthOutput = getValueAndMessage(maxLength);
465
- const minLengthOutput = getValueAndMessage(minLength);
466
- const exceedMax = !isNullOrUndefined(maxLengthOutput.value) && inputValue.length > +maxLengthOutput.value;
467
- const exceedMin = !isNullOrUndefined(minLengthOutput.value) && inputValue.length < +minLengthOutput.value;
468
- if (exceedMax || exceedMin) {
469
- getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
470
- if (!validateAllFieldCriteria) {
471
- setCustomValidity(error[name].message);
472
- return error;
473
- }
474
- }
475
- }
476
- if (pattern && !isEmpty && isString(inputValue)) {
477
- const { value: patternValue, message } = getValueAndMessage(pattern);
478
- if (isRegex(patternValue) && !inputValue.match(patternValue)) {
479
- error[name] = {
480
- type: INPUT_VALIDATION_RULES.pattern,
481
- message,
482
- ref,
483
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message)
484
- };
485
- if (!validateAllFieldCriteria) {
486
- setCustomValidity(message);
487
- return error;
488
- }
489
- }
490
- }
491
- if (validate) {
492
- if (isFunction(validate)) {
493
- const result = await validate(inputValue, formValues);
494
- const validateError = getValidateError(result, inputRef);
495
- if (validateError) {
496
- error[name] = {
497
- ...validateError,
498
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message)
499
- };
500
- if (!validateAllFieldCriteria) {
501
- setCustomValidity(validateError.message);
502
- return error;
503
- }
504
- }
505
- } else if (isObject(validate)) {
506
- let validationResult = {};
507
- for (const key in validate) {
508
- if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
509
- break;
510
- }
511
- const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
512
- if (validateError) {
513
- validationResult = {
514
- ...validateError,
515
- ...appendErrorsCurry(key, validateError.message)
516
- };
517
- setCustomValidity(validateError.message);
518
- if (validateAllFieldCriteria) {
519
- error[name] = validationResult;
520
- }
521
- }
522
- }
523
- if (!isEmptyObject(validationResult)) {
524
- error[name] = {
525
- ref: inputRef,
526
- ...validationResult
527
- };
528
- if (!validateAllFieldCriteria) {
529
- return error;
530
- }
531
- }
532
- }
533
- }
534
- setCustomValidity(true);
535
- return error;
536
- };
537
- function baseGet(object, updatePath) {
538
- const length = updatePath.slice(0, -1).length;
539
- let index = 0;
540
- while (index < length) {
541
- object = isUndefined(object) ? index++ : object[updatePath[index++]];
542
- }
543
- return object;
544
- }
545
- function isEmptyArray(obj) {
546
- for (const key in obj) {
547
- if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
548
- return false;
549
- }
550
- }
551
- return true;
552
- }
553
- function unset(object, path) {
554
- const paths = Array.isArray(path) ? path : isKey(path) ? [path] : stringToPath(path);
555
- const childObject = paths.length === 1 ? object : baseGet(object, paths);
556
- const index = paths.length - 1;
557
- const key = paths[index];
558
- if (childObject) {
559
- delete childObject[key];
560
- }
561
- if (index !== 0 && (isObject(childObject) && isEmptyObject(childObject) || Array.isArray(childObject) && isEmptyArray(childObject))) {
562
- unset(object, paths.slice(0, -1));
563
- }
564
- return object;
565
- }
566
- var createSubject = () => {
567
- let _observers = [];
568
- const next = (value) => {
569
- for (const observer of _observers) {
570
- observer.next && observer.next(value);
571
- }
572
- };
573
- const subscribe = (observer) => {
574
- _observers.push(observer);
575
- return {
576
- unsubscribe: () => {
577
- _observers = _observers.filter((o) => o !== observer);
578
- }
579
- };
580
- };
581
- const unsubscribe = () => {
582
- _observers = [];
583
- };
584
- return {
585
- get observers() {
586
- return _observers;
587
- },
588
- next,
589
- subscribe,
590
- unsubscribe
591
- };
592
- };
593
- var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
594
- function deepEqual(object1, object2) {
595
- if (isPrimitive(object1) || isPrimitive(object2)) {
596
- return object1 === object2;
597
- }
598
- if (isDateObject(object1) && isDateObject(object2)) {
599
- return object1.getTime() === object2.getTime();
600
- }
601
- const keys1 = Object.keys(object1);
602
- const keys2 = Object.keys(object2);
603
- if (keys1.length !== keys2.length) {
604
- return false;
605
- }
606
- for (const key of keys1) {
607
- const val1 = object1[key];
608
- if (!keys2.includes(key)) {
609
- return false;
610
- }
611
- if (key !== "ref") {
612
- const val2 = object2[key];
613
- if (isDateObject(val1) && isDateObject(val2) || isObject(val1) && isObject(val2) || Array.isArray(val1) && Array.isArray(val2) ? !deepEqual(val1, val2) : val1 !== val2) {
614
- return false;
615
- }
616
- }
617
- }
618
- return true;
619
- }
620
- var isMultipleSelect = (element) => element.type === `select-multiple`;
621
- var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
622
- var live = (ref) => isHTMLElement(ref) && ref.isConnected;
623
- var objectHasFunction = (data) => {
624
- for (const key in data) {
625
- if (isFunction(data[key])) {
626
- return true;
627
- }
628
- }
629
- return false;
630
- };
631
- function markFieldsDirty(data, fields = {}) {
632
- const isParentNodeArray = Array.isArray(data);
633
- if (isObject(data) || isParentNodeArray) {
634
- for (const key in data) {
635
- if (Array.isArray(data[key]) || isObject(data[key]) && !objectHasFunction(data[key])) {
636
- fields[key] = Array.isArray(data[key]) ? [] : {};
637
- markFieldsDirty(data[key], fields[key]);
638
- } else if (!isNullOrUndefined(data[key])) {
639
- fields[key] = true;
640
- }
641
- }
642
- }
643
- return fields;
644
- }
645
- function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
646
- const isParentNodeArray = Array.isArray(data);
647
- if (isObject(data) || isParentNodeArray) {
648
- for (const key in data) {
649
- if (Array.isArray(data[key]) || isObject(data[key]) && !objectHasFunction(data[key])) {
650
- if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) {
651
- dirtyFieldsFromValues[key] = Array.isArray(data[key]) ? markFieldsDirty(data[key], []) : { ...markFieldsDirty(data[key]) };
652
- } else {
653
- getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
654
- }
655
- } else {
656
- dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
657
- }
658
- }
659
- }
660
- return dirtyFieldsFromValues;
661
- }
662
- var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
663
- var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value) ? value : valueAsNumber ? value === "" ? NaN : value ? +value : value : valueAsDate && isString(value) ? new Date(value) : setValueAs ? setValueAs(value) : value;
664
- function getFieldValue(_f) {
665
- const ref = _f.ref;
666
- if (_f.refs ? _f.refs.every((ref2) => ref2.disabled) : ref.disabled) {
667
- return;
668
- }
669
- if (isFileInput(ref)) {
670
- return ref.files;
671
- }
672
- if (isRadioInput(ref)) {
673
- return getRadioValue(_f.refs).value;
674
- }
675
- if (isMultipleSelect(ref)) {
676
- return [...ref.selectedOptions].map(({ value }) => value);
677
- }
678
- if (isCheckBoxInput(ref)) {
679
- return getCheckboxValue(_f.refs).value;
680
- }
681
- return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
682
- }
683
- var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
684
- const fields = {};
685
- for (const name of fieldsNames) {
686
- const field = get(_fields, name);
687
- field && set(fields, name, field._f);
688
- }
689
- return {
690
- criteriaMode,
691
- names: [...fieldsNames],
692
- fields,
693
- shouldUseNativeValidation
694
- };
695
- };
696
- var getRuleValue = (rule) => isUndefined(rule) ? rule : isRegex(rule) ? rule.source : isObject(rule) ? isRegex(rule.value) ? rule.value.source : rule.value : rule;
697
- var hasValidation = (options) => options.mount && (options.required || options.min || options.max || options.maxLength || options.minLength || options.pattern || options.validate);
698
- function schemaErrorLookup(errors, _fields, name) {
699
- const error = get(errors, name);
700
- if (error || isKey(name)) {
701
- return {
702
- error,
703
- name
704
- };
705
- }
706
- const names = name.split(".");
707
- while (names.length) {
708
- const fieldName = names.join(".");
709
- const field = get(_fields, fieldName);
710
- const foundError = get(errors, fieldName);
711
- if (field && !Array.isArray(field) && name !== fieldName) {
712
- return { name };
713
- }
714
- if (foundError && foundError.type) {
715
- return {
716
- name: fieldName,
717
- error: foundError
718
- };
719
- }
720
- names.pop();
721
- }
722
- return {
723
- name
724
- };
725
- }
726
- var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
727
- if (mode.isOnAll) {
728
- return false;
729
- } else if (!isSubmitted && mode.isOnTouch) {
730
- return !(isTouched || isBlurEvent);
731
- } else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
732
- return !isBlurEvent;
733
- } else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
734
- return isBlurEvent;
735
- }
736
- return true;
737
- };
738
- var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
739
- const defaultOptions = {
740
- mode: VALIDATION_MODE.onSubmit,
741
- reValidateMode: VALIDATION_MODE.onChange,
742
- shouldFocusError: true
743
- };
744
- function createFormControl(props = {}, flushRootRender) {
745
- let _options = {
746
- ...defaultOptions,
747
- ...props
748
- };
749
- let _formState = {
750
- submitCount: 0,
751
- isDirty: false,
752
- isLoading: isFunction(_options.defaultValues),
753
- isValidating: false,
754
- isSubmitted: false,
755
- isSubmitting: false,
756
- isSubmitSuccessful: false,
757
- isValid: false,
758
- touchedFields: {},
759
- dirtyFields: {},
760
- errors: _options.errors || {},
761
- disabled: false
762
- };
763
- let _fields = {};
764
- let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values) ? cloneObject(_options.defaultValues || _options.values) || {} : {};
765
- let _formValues = _options.shouldUnregister ? {} : cloneObject(_defaultValues);
766
- let _state = {
767
- action: false,
768
- mount: false,
769
- watch: false
770
- };
771
- let _names = {
772
- mount: /* @__PURE__ */ new Set(),
773
- unMount: /* @__PURE__ */ new Set(),
774
- array: /* @__PURE__ */ new Set(),
775
- watch: /* @__PURE__ */ new Set()
776
- };
777
- let delayErrorCallback;
778
- let timer = 0;
779
- const _proxyFormState = {
780
- isDirty: false,
781
- dirtyFields: false,
782
- touchedFields: false,
783
- isValidating: false,
784
- isValid: false,
785
- errors: false
786
- };
787
- const _subjects = {
788
- values: createSubject(),
789
- array: createSubject(),
790
- state: createSubject()
791
- };
792
- const shouldCaptureDirtyFields = props.resetOptions && props.resetOptions.keepDirtyValues;
793
- const validationModeBeforeSubmit = getValidationModes(_options.mode);
794
- const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
795
- const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
796
- const debounce = (callback) => (wait) => {
797
- clearTimeout(timer);
798
- timer = setTimeout(callback, wait);
799
- };
800
- const _updateValid = async (shouldUpdateValid) => {
801
- if (_proxyFormState.isValid || shouldUpdateValid) {
802
- const isValid = _options.resolver ? isEmptyObject((await _executeSchema()).errors) : await executeBuiltInValidation(_fields, true);
803
- if (isValid !== _formState.isValid) {
804
- _subjects.state.next({
805
- isValid
806
- });
807
- }
808
- }
809
- };
810
- const _updateIsValidating = (value) => _proxyFormState.isValidating && _subjects.state.next({
811
- isValidating: value
812
- });
813
- const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
814
- if (args && method) {
815
- _state.action = true;
816
- if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
817
- const fieldValues = method(get(_fields, name), args.argA, args.argB);
818
- shouldSetValues && set(_fields, name, fieldValues);
819
- }
820
- if (shouldUpdateFieldsAndState && Array.isArray(get(_formState.errors, name))) {
821
- const errors = method(get(_formState.errors, name), args.argA, args.argB);
822
- shouldSetValues && set(_formState.errors, name, errors);
823
- unsetEmptyArray(_formState.errors, name);
824
- }
825
- if (_proxyFormState.touchedFields && shouldUpdateFieldsAndState && Array.isArray(get(_formState.touchedFields, name))) {
826
- const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
827
- shouldSetValues && set(_formState.touchedFields, name, touchedFields);
828
- }
829
- if (_proxyFormState.dirtyFields) {
830
- _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
831
- }
832
- _subjects.state.next({
833
- name,
834
- isDirty: _getDirty(name, values),
835
- dirtyFields: _formState.dirtyFields,
836
- errors: _formState.errors,
837
- isValid: _formState.isValid
838
- });
839
- } else {
840
- set(_formValues, name, values);
841
- }
842
- };
843
- const updateErrors = (name, error) => {
844
- set(_formState.errors, name, error);
845
- _subjects.state.next({
846
- errors: _formState.errors
847
- });
848
- };
849
- const _setErrors = (errors) => {
850
- _formState.errors = errors;
851
- _subjects.state.next({
852
- errors: _formState.errors,
853
- isValid: false
854
- });
855
- };
856
- const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
857
- const field = get(_fields, name);
858
- if (field) {
859
- const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
860
- isUndefined(defaultValue) || ref && ref.defaultChecked || shouldSkipSetValueAs ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f)) : setFieldValue(name, defaultValue);
861
- _state.mount && _updateValid();
862
- }
863
- };
864
- const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
865
- let shouldUpdateField = false;
866
- let isPreviousDirty = false;
867
- const output = {
868
- name
869
- };
870
- const disabledField = get(_fields, name) && get(_fields, name)._f.disabled;
871
- if (!isBlurEvent || shouldDirty) {
872
- if (_proxyFormState.isDirty) {
873
- isPreviousDirty = _formState.isDirty;
874
- _formState.isDirty = output.isDirty = _getDirty();
875
- shouldUpdateField = isPreviousDirty !== output.isDirty;
876
- }
877
- const isCurrentFieldPristine = disabledField || deepEqual(get(_defaultValues, name), fieldValue);
878
- isPreviousDirty = !disabledField && get(_formState.dirtyFields, name);
879
- isCurrentFieldPristine || disabledField ? unset(_formState.dirtyFields, name) : set(_formState.dirtyFields, name, true);
880
- output.dirtyFields = _formState.dirtyFields;
881
- shouldUpdateField = shouldUpdateField || _proxyFormState.dirtyFields && isPreviousDirty !== !isCurrentFieldPristine;
882
- }
883
- if (isBlurEvent) {
884
- const isPreviousFieldTouched = get(_formState.touchedFields, name);
885
- if (!isPreviousFieldTouched) {
886
- set(_formState.touchedFields, name, isBlurEvent);
887
- output.touchedFields = _formState.touchedFields;
888
- shouldUpdateField = shouldUpdateField || _proxyFormState.touchedFields && isPreviousFieldTouched !== isBlurEvent;
889
- }
890
- }
891
- shouldUpdateField && shouldRender && _subjects.state.next(output);
892
- return shouldUpdateField ? output : {};
893
- };
894
- const shouldRenderByError = (name, isValid, error, fieldState) => {
895
- const previousFieldError = get(_formState.errors, name);
896
- const shouldUpdateValid = _proxyFormState.isValid && isBoolean(isValid) && _formState.isValid !== isValid;
897
- if (props.delayError && error) {
898
- delayErrorCallback = debounce(() => updateErrors(name, error));
899
- delayErrorCallback(props.delayError);
900
- } else {
901
- clearTimeout(timer);
902
- delayErrorCallback = null;
903
- error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
904
- }
905
- if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) || !isEmptyObject(fieldState) || shouldUpdateValid) {
906
- const updatedFormState = {
907
- ...fieldState,
908
- ...shouldUpdateValid && isBoolean(isValid) ? { isValid } : {},
909
- errors: _formState.errors,
910
- name
911
- };
912
- _formState = {
913
- ..._formState,
914
- ...updatedFormState
915
- };
916
- _subjects.state.next(updatedFormState);
917
- }
918
- _updateIsValidating(false);
919
- };
920
- const _executeSchema = async (name) => _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
921
- const executeSchemaAndUpdateState = async (names) => {
922
- const { errors } = await _executeSchema(names);
923
- if (names) {
924
- for (const name of names) {
925
- const error = get(errors, name);
926
- error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
927
- }
928
- } else {
929
- _formState.errors = errors;
930
- }
931
- return errors;
932
- };
933
- const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
934
- valid: true
935
- }) => {
936
- for (const name in fields) {
937
- const field = fields[name];
938
- if (field) {
939
- const { _f, ...fieldValue } = field;
940
- if (_f) {
941
- const isFieldArrayRoot = _names.array.has(_f.name);
942
- const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
943
- if (fieldError[_f.name]) {
944
- context.valid = false;
945
- if (shouldOnlyCheckValid) {
946
- break;
947
- }
948
- }
949
- !shouldOnlyCheckValid && (get(fieldError, _f.name) ? isFieldArrayRoot ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name) : set(_formState.errors, _f.name, fieldError[_f.name]) : unset(_formState.errors, _f.name));
950
- }
951
- fieldValue && await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context);
952
- }
953
- }
954
- return context.valid;
955
- };
956
- const _removeUnmounted = () => {
957
- for (const name of _names.unMount) {
958
- const field = get(_fields, name);
959
- field && (field._f.refs ? field._f.refs.every((ref) => !live(ref)) : !live(field._f.ref)) && unregister(name);
960
- }
961
- _names.unMount = /* @__PURE__ */ new Set();
962
- };
963
- const _getDirty = (name, data) => (name && data && set(_formValues, name, data), !deepEqual(getValues(), _defaultValues));
964
- const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
965
- ..._state.mount ? _formValues : isUndefined(defaultValue) ? _defaultValues : isString(names) ? { [names]: defaultValue } : defaultValue
966
- }, isGlobal, defaultValue);
967
- const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
968
- const setFieldValue = (name, value, options = {}) => {
969
- const field = get(_fields, name);
970
- let fieldValue = value;
971
- if (field) {
972
- const fieldReference = field._f;
973
- if (fieldReference) {
974
- !fieldReference.disabled && set(_formValues, name, getFieldValueAs(value, fieldReference));
975
- fieldValue = isHTMLElement(fieldReference.ref) && isNullOrUndefined(value) ? "" : value;
976
- if (isMultipleSelect(fieldReference.ref)) {
977
- [...fieldReference.ref.options].forEach((optionRef) => optionRef.selected = fieldValue.includes(optionRef.value));
978
- } else if (fieldReference.refs) {
979
- if (isCheckBoxInput(fieldReference.ref)) {
980
- fieldReference.refs.length > 1 ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) && (checkboxRef.checked = Array.isArray(fieldValue) ? !!fieldValue.find((data) => data === checkboxRef.value) : fieldValue === checkboxRef.value)) : fieldReference.refs[0] && (fieldReference.refs[0].checked = !!fieldValue);
981
- } else {
982
- fieldReference.refs.forEach((radioRef) => radioRef.checked = radioRef.value === fieldValue);
983
- }
984
- } else if (isFileInput(fieldReference.ref)) {
985
- fieldReference.ref.value = "";
986
- } else {
987
- fieldReference.ref.value = fieldValue;
988
- if (!fieldReference.ref.type) {
989
- _subjects.values.next({
990
- name,
991
- values: { ..._formValues }
992
- });
993
- }
994
- }
995
- }
996
- }
997
- (options.shouldDirty || options.shouldTouch) && updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
998
- options.shouldValidate && trigger(name);
999
- };
1000
- const setValues = (name, value, options) => {
1001
- for (const fieldKey in value) {
1002
- const fieldValue = value[fieldKey];
1003
- const fieldName = `${name}.${fieldKey}`;
1004
- const field = get(_fields, fieldName);
1005
- (_names.array.has(name) || !isPrimitive(fieldValue) || field && !field._f) && !isDateObject(fieldValue) ? setValues(fieldName, fieldValue, options) : setFieldValue(fieldName, fieldValue, options);
1006
- }
1007
- };
1008
- const setValue = (name, value, options = {}) => {
1009
- const field = get(_fields, name);
1010
- const isFieldArray = _names.array.has(name);
1011
- const cloneValue = cloneObject(value);
1012
- set(_formValues, name, cloneValue);
1013
- if (isFieldArray) {
1014
- _subjects.array.next({
1015
- name,
1016
- values: { ..._formValues }
1017
- });
1018
- if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) && options.shouldDirty) {
1019
- _subjects.state.next({
1020
- name,
1021
- dirtyFields: getDirtyFields(_defaultValues, _formValues),
1022
- isDirty: _getDirty(name, cloneValue)
1023
- });
1024
- }
1025
- } else {
1026
- field && !field._f && !isNullOrUndefined(cloneValue) ? setValues(name, cloneValue, options) : setFieldValue(name, cloneValue, options);
1027
- }
1028
- isWatched(name, _names) && _subjects.state.next({ ..._formState });
1029
- _subjects.values.next({
1030
- name,
1031
- values: { ..._formValues }
1032
- });
1033
- !_state.mount && flushRootRender();
1034
- };
1035
- const onChange = async (event) => {
1036
- const target = event.target;
1037
- let name = target.name;
1038
- let isFieldValueUpdated = true;
1039
- const field = get(_fields, name);
1040
- const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
1041
- const _updateIsFieldValueUpdated = (fieldValue) => {
1042
- isFieldValueUpdated = Number.isNaN(fieldValue) || fieldValue === get(_formValues, name, fieldValue);
1043
- };
1044
- if (field) {
1045
- let error;
1046
- let isValid;
1047
- const fieldValue = getCurrentFieldValue();
1048
- const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1049
- const shouldSkipValidation = !hasValidation(field._f) && !_options.resolver && !get(_formState.errors, name) && !field._f.deps || skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
1050
- const watched = isWatched(name, _names, isBlurEvent);
1051
- set(_formValues, name, fieldValue);
1052
- if (isBlurEvent) {
1053
- field._f.onBlur && field._f.onBlur(event);
1054
- delayErrorCallback && delayErrorCallback(0);
1055
- } else if (field._f.onChange) {
1056
- field._f.onChange(event);
1057
- }
1058
- const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
1059
- const shouldRender = !isEmptyObject(fieldState) || watched;
1060
- !isBlurEvent && _subjects.values.next({
1061
- name,
1062
- type: event.type,
1063
- values: { ..._formValues }
1064
- });
1065
- if (shouldSkipValidation) {
1066
- _proxyFormState.isValid && _updateValid();
1067
- return shouldRender && _subjects.state.next({ name, ...watched ? {} : fieldState });
1068
- }
1069
- !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1070
- _updateIsValidating(true);
1071
- if (_options.resolver) {
1072
- const { errors } = await _executeSchema([name]);
1073
- _updateIsFieldValueUpdated(fieldValue);
1074
- if (isFieldValueUpdated) {
1075
- const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1076
- const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1077
- error = errorLookupResult.error;
1078
- name = errorLookupResult.name;
1079
- isValid = isEmptyObject(errors);
1080
- }
1081
- } else {
1082
- error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1083
- _updateIsFieldValueUpdated(fieldValue);
1084
- if (isFieldValueUpdated) {
1085
- if (error) {
1086
- isValid = false;
1087
- } else if (_proxyFormState.isValid) {
1088
- isValid = await executeBuiltInValidation(_fields, true);
1089
- }
1090
- }
1091
- }
1092
- if (isFieldValueUpdated) {
1093
- field._f.deps && trigger(field._f.deps);
1094
- shouldRenderByError(name, isValid, error, fieldState);
1095
- }
1096
- }
1097
- };
1098
- const _focusInput = (ref, key) => {
1099
- if (get(_formState.errors, key) && ref.focus) {
1100
- ref.focus();
1101
- return 1;
1102
- }
1103
- return;
1104
- };
1105
- const trigger = async (name, options = {}) => {
1106
- let isValid;
1107
- let validationResult;
1108
- const fieldNames = convertToArrayPayload(name);
1109
- _updateIsValidating(true);
1110
- if (_options.resolver) {
1111
- const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1112
- isValid = isEmptyObject(errors);
1113
- validationResult = name ? !fieldNames.some((name2) => get(errors, name2)) : isValid;
1114
- } else if (name) {
1115
- validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1116
- const field = get(_fields, fieldName);
1117
- return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
1118
- }))).every(Boolean);
1119
- !(!validationResult && !_formState.isValid) && _updateValid();
1120
- } else {
1121
- validationResult = isValid = await executeBuiltInValidation(_fields);
1122
- }
1123
- _subjects.state.next({
1124
- ...!isString(name) || _proxyFormState.isValid && isValid !== _formState.isValid ? {} : { name },
1125
- ..._options.resolver || !name ? { isValid } : {},
1126
- errors: _formState.errors,
1127
- isValidating: false
1128
- });
1129
- options.shouldFocus && !validationResult && iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
1130
- return validationResult;
1131
- };
1132
- const getValues = (fieldNames) => {
1133
- const values = {
1134
- ..._defaultValues,
1135
- ..._state.mount ? _formValues : {}
1136
- };
1137
- return isUndefined(fieldNames) ? values : isString(fieldNames) ? get(values, fieldNames) : fieldNames.map((name) => get(values, name));
1138
- };
1139
- const getFieldState = (name, formState) => ({
1140
- invalid: !!get((formState || _formState).errors, name),
1141
- isDirty: !!get((formState || _formState).dirtyFields, name),
1142
- isTouched: !!get((formState || _formState).touchedFields, name),
1143
- error: get((formState || _formState).errors, name)
1144
- });
1145
- const clearErrors = (name) => {
1146
- name && convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
1147
- _subjects.state.next({
1148
- errors: name ? _formState.errors : {}
1149
- });
1150
- };
1151
- const setError = (name, error, options) => {
1152
- const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1153
- set(_formState.errors, name, {
1154
- ...error,
1155
- ref
1156
- });
1157
- _subjects.state.next({
1158
- name,
1159
- errors: _formState.errors,
1160
- isValid: false
1161
- });
1162
- options && options.shouldFocus && ref && ref.focus && ref.focus();
1163
- };
1164
- const watch = (name, defaultValue) => isFunction(name) ? _subjects.values.subscribe({
1165
- next: (payload) => name(_getWatch(void 0, defaultValue), payload)
1166
- }) : _getWatch(name, defaultValue, true);
1167
- const unregister = (name, options = {}) => {
1168
- for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1169
- _names.mount.delete(fieldName);
1170
- _names.array.delete(fieldName);
1171
- if (!options.keepValue) {
1172
- unset(_fields, fieldName);
1173
- unset(_formValues, fieldName);
1174
- }
1175
- !options.keepError && unset(_formState.errors, fieldName);
1176
- !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1177
- !options.keepTouched && unset(_formState.touchedFields, fieldName);
1178
- !_options.shouldUnregister && !options.keepDefaultValue && unset(_defaultValues, fieldName);
1179
- }
1180
- _subjects.values.next({
1181
- values: { ..._formValues }
1182
- });
1183
- _subjects.state.next({
1184
- ..._formState,
1185
- ...!options.keepDirty ? {} : { isDirty: _getDirty() }
1186
- });
1187
- !options.keepIsValid && _updateValid();
1188
- };
1189
- const _updateDisabledField = ({ disabled, name, field, fields, value }) => {
1190
- if (isBoolean(disabled)) {
1191
- const inputValue = disabled ? void 0 : isUndefined(value) ? getFieldValue(field ? field._f : get(fields, name)._f) : value;
1192
- set(_formValues, name, inputValue);
1193
- updateTouchAndDirty(name, inputValue, false, false, true);
1194
- }
1195
- };
1196
- const register = (name, options = {}) => {
1197
- let field = get(_fields, name);
1198
- const disabledIsDefined = isBoolean(options.disabled);
1199
- set(_fields, name, {
1200
- ...field || {},
1201
- _f: {
1202
- ...field && field._f ? field._f : { ref: { name } },
1203
- name,
1204
- mount: true,
1205
- ...options
1206
- }
1207
- });
1208
- _names.mount.add(name);
1209
- if (field) {
1210
- _updateDisabledField({
1211
- field,
1212
- disabled: options.disabled,
1213
- name
1214
- });
1215
- } else {
1216
- updateValidAndValue(name, true, options.value);
1217
- }
1218
- return {
1219
- ...disabledIsDefined ? { disabled: options.disabled } : {},
1220
- ..._options.progressive ? {
1221
- required: !!options.required,
1222
- min: getRuleValue(options.min),
1223
- max: getRuleValue(options.max),
1224
- minLength: getRuleValue(options.minLength),
1225
- maxLength: getRuleValue(options.maxLength),
1226
- pattern: getRuleValue(options.pattern)
1227
- } : {},
1228
- name,
1229
- onChange,
1230
- onBlur: onChange,
1231
- ref: (ref) => {
1232
- if (ref) {
1233
- register(name, options);
1234
- field = get(_fields, name);
1235
- const fieldRef = isUndefined(ref.value) ? ref.querySelectorAll ? ref.querySelectorAll("input,select,textarea")[0] || ref : ref : ref;
1236
- const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1237
- const refs = field._f.refs || [];
1238
- if (radioOrCheckbox ? refs.find((option) => option === fieldRef) : fieldRef === field._f.ref) {
1239
- return;
1240
- }
1241
- set(_fields, name, {
1242
- _f: {
1243
- ...field._f,
1244
- ...radioOrCheckbox ? {
1245
- refs: [
1246
- ...refs.filter(live),
1247
- fieldRef,
1248
- ...Array.isArray(get(_defaultValues, name)) ? [{}] : []
1249
- ],
1250
- ref: { type: fieldRef.type, name }
1251
- } : { ref: fieldRef }
1252
- }
1253
- });
1254
- updateValidAndValue(name, false, void 0, fieldRef);
1255
- } else {
1256
- field = get(_fields, name, {});
1257
- if (field._f) {
1258
- field._f.mount = false;
1259
- }
1260
- (_options.shouldUnregister || options.shouldUnregister) && !(isNameInFieldArray(_names.array, name) && _state.action) && _names.unMount.add(name);
1261
- }
1262
- }
1263
- };
1264
- };
1265
- const _focusError = () => _options.shouldFocusError && iterateFieldsByAction(_fields, _focusInput, _names.mount);
1266
- const _disableForm = (disabled) => {
1267
- if (isBoolean(disabled)) {
1268
- _subjects.state.next({ disabled });
1269
- iterateFieldsByAction(_fields, (ref, name) => {
1270
- let requiredDisabledState = disabled;
1271
- const currentField = get(_fields, name);
1272
- if (currentField && isBoolean(currentField._f.disabled)) {
1273
- requiredDisabledState || (requiredDisabledState = currentField._f.disabled);
1274
- }
1275
- ref.disabled = requiredDisabledState;
1276
- }, 0, false);
1277
- }
1278
- };
1279
- const handleSubmit = (onValid, onInvalid) => async (e) => {
1280
- if (e) {
1281
- e.preventDefault && e.preventDefault();
1282
- e.persist && e.persist();
1283
- }
1284
- let fieldValues = cloneObject(_formValues);
1285
- _subjects.state.next({
1286
- isSubmitting: true
1287
- });
1288
- if (_options.resolver) {
1289
- const { errors, values } = await _executeSchema();
1290
- _formState.errors = errors;
1291
- fieldValues = values;
1292
- } else {
1293
- await executeBuiltInValidation(_fields);
1294
- }
1295
- unset(_formState.errors, "root");
1296
- if (isEmptyObject(_formState.errors)) {
1297
- _subjects.state.next({
1298
- errors: {}
1299
- });
1300
- await onValid(fieldValues, e);
1301
- } else {
1302
- if (onInvalid) {
1303
- await onInvalid({ ..._formState.errors }, e);
1304
- }
1305
- _focusError();
1306
- setTimeout(_focusError);
1307
- }
1308
- _subjects.state.next({
1309
- isSubmitted: true,
1310
- isSubmitting: false,
1311
- isSubmitSuccessful: isEmptyObject(_formState.errors),
1312
- submitCount: _formState.submitCount + 1,
1313
- errors: _formState.errors
1314
- });
1315
- };
1316
- const resetField = (name, options = {}) => {
1317
- if (get(_fields, name)) {
1318
- if (isUndefined(options.defaultValue)) {
1319
- setValue(name, get(_defaultValues, name));
1320
- } else {
1321
- setValue(name, options.defaultValue);
1322
- set(_defaultValues, name, options.defaultValue);
1323
- }
1324
- if (!options.keepTouched) {
1325
- unset(_formState.touchedFields, name);
1326
- }
1327
- if (!options.keepDirty) {
1328
- unset(_formState.dirtyFields, name);
1329
- _formState.isDirty = options.defaultValue ? _getDirty(name, get(_defaultValues, name)) : _getDirty();
1330
- }
1331
- if (!options.keepError) {
1332
- unset(_formState.errors, name);
1333
- _proxyFormState.isValid && _updateValid();
1334
- }
1335
- _subjects.state.next({ ..._formState });
1336
- }
1337
- };
1338
- const _reset = (formValues, keepStateOptions = {}) => {
1339
- const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
1340
- const cloneUpdatedValues = cloneObject(updatedValues);
1341
- const values = formValues && !isEmptyObject(formValues) ? cloneUpdatedValues : _defaultValues;
1342
- if (!keepStateOptions.keepDefaultValues) {
1343
- _defaultValues = updatedValues;
1344
- }
1345
- if (!keepStateOptions.keepValues) {
1346
- if (keepStateOptions.keepDirtyValues || shouldCaptureDirtyFields) {
1347
- for (const fieldName of _names.mount) {
1348
- get(_formState.dirtyFields, fieldName) ? set(values, fieldName, get(_formValues, fieldName)) : setValue(fieldName, get(values, fieldName));
1349
- }
1350
- } else {
1351
- if (isWeb && isUndefined(formValues)) {
1352
- for (const name of _names.mount) {
1353
- const field = get(_fields, name);
1354
- if (field && field._f) {
1355
- const fieldReference = Array.isArray(field._f.refs) ? field._f.refs[0] : field._f.ref;
1356
- if (isHTMLElement(fieldReference)) {
1357
- const form = fieldReference.closest("form");
1358
- if (form) {
1359
- form.reset();
1360
- break;
1361
- }
1362
- }
1363
- }
1364
- }
1365
- }
1366
- _fields = {};
1367
- }
1368
- _formValues = props.shouldUnregister ? keepStateOptions.keepDefaultValues ? cloneObject(_defaultValues) : {} : cloneObject(values);
1369
- _subjects.array.next({
1370
- values: { ...values }
1371
- });
1372
- _subjects.values.next({
1373
- values: { ...values }
1374
- });
1375
- }
1376
- _names = {
1377
- mount: /* @__PURE__ */ new Set(),
1378
- unMount: /* @__PURE__ */ new Set(),
1379
- array: /* @__PURE__ */ new Set(),
1380
- watch: /* @__PURE__ */ new Set(),
1381
- watchAll: false,
1382
- focus: ""
1383
- };
1384
- !_state.mount && flushRootRender();
1385
- _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid;
1386
- _state.watch = !!props.shouldUnregister;
1387
- _subjects.state.next({
1388
- submitCount: keepStateOptions.keepSubmitCount ? _formState.submitCount : 0,
1389
- isDirty: keepStateOptions.keepDirty ? _formState.isDirty : !!(keepStateOptions.keepDefaultValues && !deepEqual(formValues, _defaultValues)),
1390
- isSubmitted: keepStateOptions.keepIsSubmitted ? _formState.isSubmitted : false,
1391
- dirtyFields: keepStateOptions.keepDirtyValues ? _formState.dirtyFields : keepStateOptions.keepDefaultValues && formValues ? getDirtyFields(_defaultValues, formValues) : {},
1392
- touchedFields: keepStateOptions.keepTouched ? _formState.touchedFields : {},
1393
- errors: keepStateOptions.keepErrors ? _formState.errors : {},
1394
- isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful ? _formState.isSubmitSuccessful : false,
1395
- isSubmitting: false
1396
- });
1397
- };
1398
- const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues) ? formValues(_formValues) : formValues, keepStateOptions);
1399
- const setFocus = (name, options = {}) => {
1400
- const field = get(_fields, name);
1401
- const fieldReference = field && field._f;
1402
- if (fieldReference) {
1403
- const fieldRef = fieldReference.refs ? fieldReference.refs[0] : fieldReference.ref;
1404
- if (fieldRef.focus) {
1405
- fieldRef.focus();
1406
- options.shouldSelect && fieldRef.select();
1407
- }
1408
- }
1409
- };
1410
- const _updateFormState = (updatedFormState) => {
1411
- _formState = {
1412
- ..._formState,
1413
- ...updatedFormState
1414
- };
1415
- };
1416
- const _resetDefaultValues = () => isFunction(_options.defaultValues) && _options.defaultValues().then((values) => {
1417
- reset(values, _options.resetOptions);
1418
- _subjects.state.next({
1419
- isLoading: false
1420
- });
1421
- });
1422
- return {
1423
- control: {
1424
- register,
1425
- unregister,
1426
- getFieldState,
1427
- handleSubmit,
1428
- setError,
1429
- _executeSchema,
1430
- _getWatch,
1431
- _getDirty,
1432
- _updateValid,
1433
- _removeUnmounted,
1434
- _updateFieldArray,
1435
- _updateDisabledField,
1436
- _getFieldArray,
1437
- _reset,
1438
- _resetDefaultValues,
1439
- _updateFormState,
1440
- _disableForm,
1441
- _subjects,
1442
- _proxyFormState,
1443
- _setErrors,
1444
- get _fields() {
1445
- return _fields;
1446
- },
1447
- get _formValues() {
1448
- return _formValues;
1449
- },
1450
- get _state() {
1451
- return _state;
1452
- },
1453
- set _state(value) {
1454
- _state = value;
1455
- },
1456
- get _defaultValues() {
1457
- return _defaultValues;
1458
- },
1459
- get _names() {
1460
- return _names;
1461
- },
1462
- set _names(value) {
1463
- _names = value;
1464
- },
1465
- get _formState() {
1466
- return _formState;
1467
- },
1468
- set _formState(value) {
1469
- _formState = value;
1470
- },
1471
- get _options() {
1472
- return _options;
1473
- },
1474
- set _options(value) {
1475
- _options = {
1476
- ..._options,
1477
- ...value
1478
- };
1479
- }
1480
- },
1481
- trigger,
1482
- register,
1483
- handleSubmit,
1484
- watch,
1485
- setValue,
1486
- getValues,
1487
- reset,
1488
- resetField,
1489
- clearErrors,
1490
- unregister,
1491
- setError,
1492
- setFocus,
1493
- getFieldState
1494
- };
1495
- }
1496
- function useForm(props = {}) {
1497
- const _formControl = React.useRef();
1498
- const _values = React.useRef();
1499
- const [formState, updateFormState] = React.useState({
1500
- isDirty: false,
1501
- isValidating: false,
1502
- isLoading: isFunction(props.defaultValues),
1503
- isSubmitted: false,
1504
- isSubmitting: false,
1505
- isSubmitSuccessful: false,
1506
- isValid: false,
1507
- submitCount: 0,
1508
- dirtyFields: {},
1509
- touchedFields: {},
1510
- errors: props.errors || {},
1511
- disabled: false,
1512
- defaultValues: isFunction(props.defaultValues) ? void 0 : props.defaultValues
1513
- });
1514
- if (!_formControl.current) {
1515
- _formControl.current = {
1516
- ...createFormControl(props, () => updateFormState((formState2) => ({ ...formState2 }))),
1517
- formState
1518
- };
1519
- }
1520
- const control = _formControl.current.control;
1521
- control._options = props;
1522
- useSubscribe({
1523
- subject: control._subjects.state,
1524
- next: (value) => {
1525
- if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
1526
- updateFormState({ ...control._formState });
1527
- }
1528
- }
1529
- });
1530
- React.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
1531
- React.useEffect(() => {
1532
- if (control._proxyFormState.isDirty) {
1533
- const isDirty = control._getDirty();
1534
- if (isDirty !== formState.isDirty) {
1535
- control._subjects.state.next({
1536
- isDirty
1537
- });
1538
- }
1539
- }
1540
- }, [control, formState.isDirty]);
1541
- React.useEffect(() => {
1542
- if (props.values && !deepEqual(props.values, _values.current)) {
1543
- control._reset(props.values, control._options.resetOptions);
1544
- _values.current = props.values;
1545
- updateFormState((state) => ({ ...state }));
1546
- } else {
1547
- control._resetDefaultValues();
1548
- }
1549
- }, [props.values, control]);
1550
- React.useEffect(() => {
1551
- if (props.errors) {
1552
- control._setErrors(props.errors);
1553
- }
1554
- }, [props.errors, control]);
1555
- React.useEffect(() => {
1556
- if (!control._state.mount) {
1557
- control._updateValid();
1558
- control._state.mount = true;
1559
- }
1560
- if (control._state.watch) {
1561
- control._state.watch = false;
1562
- control._subjects.state.next({ ...control._formState });
1563
- }
1564
- control._removeUnmounted();
1565
- });
1566
- _formControl.current.formState = getProxyFormState(formState, control);
1567
- return _formControl.current;
1568
- }
1569
- const QuickBooksSettingsPage = () => {
1570
- const [settings, setSettings] = useState(null);
1571
- const [connection, setConnection] = useState(null);
1572
- const [isLoading, setIsLoading] = useState(true);
1573
- const [isSaving, setIsSaving] = useState(false);
1574
- const { control, handleSubmit, reset } = useForm({
1575
- defaultValues: {
1576
- auto_sync_customers: false,
1577
- auto_sync_products: false,
1578
- auto_sync_orders: false,
1579
- reverse_sync_customers: false,
1580
- reverse_sync_products: false,
1581
- reverse_sync_orders: false
1582
- }
1583
- });
1584
- useEffect(() => {
1585
- fetchData();
1586
- }, []);
1587
- const fetchData = async () => {
1588
- try {
1589
- setIsLoading(true);
1590
- const connRes = await fetch("/admin/quickbooks/connection");
1591
- const connData = await connRes.json();
1592
- setConnection(connData);
1593
- const setRes = await fetch("/admin/quickbooks/settings");
1594
- const setData = await setRes.json();
1595
- if (setData.settings) {
1596
- setSettings(setData.settings);
1597
- reset(setData.settings);
1598
- }
1599
- } catch (err) {
1600
- toast.error("Failed to load QuickBooks data");
1601
- } finally {
1602
- setIsLoading(false);
1603
- }
1604
- };
1605
- const onSubmit = async (data) => {
1606
- try {
1607
- setIsSaving(true);
1608
- const res = await fetch("/admin/quickbooks/settings", {
1609
- method: "PUT",
1610
- headers: { "Content-Type": "application/json" },
1611
- body: JSON.stringify(data)
1612
- });
1613
- if (res.ok) {
1614
- toast.success("Settings saved successfully");
1615
- const updated = await res.json();
1616
- setSettings(updated.settings);
1617
- reset(updated.settings);
1618
- } else {
1619
- throw new Error("Failed to save");
1620
- }
1621
- } catch (err) {
1622
- toast.error("Failed to save settings");
1623
- } finally {
1624
- setIsSaving(false);
1625
- }
1626
- };
1627
- const handleConnect = async () => {
1628
- try {
1629
- const res = await fetch("/admin/quickbooks/connect");
1630
- const data = await res.json();
1631
- if (data.url) {
1632
- window.location.href = data.url;
1633
- } else {
1634
- toast.error("Failed to get authorization URL");
1635
- }
1636
- } catch (err) {
1637
- toast.error("Connection error");
1638
- }
1639
- };
1640
- const handleDisconnect = async () => {
1641
- if (!confirm("Are you sure you want to disconnect?")) return;
1642
- try {
1643
- const res = await fetch("/admin/quickbooks/disconnect", {
1644
- method: "POST"
1645
- });
1646
- if (res.ok) {
1647
- toast.success("Disconnected from QuickBooks");
1648
- fetchData();
1649
- } else {
1650
- toast.error("Failed to disconnect");
1651
- }
1652
- } catch (err) {
1653
- toast.error("Disconnection error");
1654
- }
1655
- };
1656
- if (isLoading) return /* @__PURE__ */ jsx(Text, { children: "Loading..." });
1657
- return /* @__PURE__ */ jsxs(Container, { className: "p-8 flex flex-col gap-y-8", children: [
1658
- /* @__PURE__ */ jsxs("div", { children: [
1659
- /* @__PURE__ */ jsx(Heading, { level: "h1", children: "QuickBooks Integration" }),
1660
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-subtle", children: "Manage your connection and synchronization settings." })
1661
- ] }),
1662
- /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-4 p-4 border rounded-lg bg-ui-bg-base", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1663
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1", children: [
1664
- /* @__PURE__ */ jsx(Heading, { level: "h2", children: "Connection Status" }),
1665
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
1666
- /* @__PURE__ */ jsx(Text, { children: "Status:" }),
1667
- (connection == null ? void 0 : connection.is_connected) ? /* @__PURE__ */ jsx(Badge, { color: "green", children: "Connected" }) : /* @__PURE__ */ jsx(Badge, { color: "red", children: "Disconnected" })
1668
- ] }),
1669
- (connection == null ? void 0 : connection.is_connected) && /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-subtle text-small", children: [
1670
- "Connected to: ",
1671
- connection.company_name,
1672
- " (Realm ID: ",
1673
- connection.realm_id,
1674
- ")"
1675
- ] })
1676
- ] }),
1677
- /* @__PURE__ */ jsx("div", { children: (connection == null ? void 0 : connection.is_connected) ? /* @__PURE__ */ jsx(Button, { variant: "danger", onClick: handleDisconnect, children: "Disconnect" }) : /* @__PURE__ */ jsx(Button, { onClick: handleConnect, children: "Connect to QuickBooks" }) })
1678
- ] }) }),
1679
- /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit(onSubmit), className: "flex flex-col gap-y-6", children: [
1680
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
1681
- /* @__PURE__ */ jsx(Heading, { level: "h2", children: "Account Mappings" }),
1682
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-subtle", children: "Enter the QuickBooks Account IDs (Numeric) for transactions." }),
1683
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
1684
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
1685
- /* @__PURE__ */ jsx(Label, { children: "Income Account ID" }),
1686
- /* @__PURE__ */ jsx(
1687
- Controller,
1688
- {
1689
- control,
1690
- name: "income_account_id",
1691
- render: ({ field }) => /* @__PURE__ */ jsx(Input, { ...field, placeholder: "e.g. 1" })
1692
- }
1693
- )
1694
- ] }),
1695
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
1696
- /* @__PURE__ */ jsx(Label, { children: "COGS Account ID" }),
1697
- /* @__PURE__ */ jsx(
1698
- Controller,
1699
- {
1700
- control,
1701
- name: "cogs_account_id",
1702
- render: ({ field }) => /* @__PURE__ */ jsx(Input, { ...field, placeholder: "e.g. 50" })
1703
- }
1704
- )
1705
- ] }),
1706
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
1707
- /* @__PURE__ */ jsx(Label, { children: "Asset Account ID" }),
1708
- /* @__PURE__ */ jsx(
1709
- Controller,
1710
- {
1711
- control,
1712
- name: "asset_account_id",
1713
- render: ({ field }) => /* @__PURE__ */ jsx(Input, { ...field, placeholder: "e.g. 80" })
1714
- }
1715
- )
1716
- ] })
1717
- ] })
1718
- ] }),
1719
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
1720
- /* @__PURE__ */ jsx(Heading, { level: "h2", children: "Synchronization Settings" }),
1721
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-8", children: [
1722
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
1723
- /* @__PURE__ */ jsx(Text, { weight: "plus", children: "Auto-Sync (Medusa to QuickBooks)" }),
1724
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1725
- /* @__PURE__ */ jsx(Label, { children: "Sync Customers" }),
1726
- /* @__PURE__ */ jsx(
1727
- Controller,
1728
- {
1729
- control,
1730
- name: "auto_sync_customers",
1731
- render: ({ field: { value, onChange } }) => /* @__PURE__ */ jsx(Switch, { checked: value, onCheckedChange: onChange })
1732
- }
1733
- )
1734
- ] }),
1735
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1736
- /* @__PURE__ */ jsx(Label, { children: "Sync Products" }),
1737
- /* @__PURE__ */ jsx(
1738
- Controller,
1739
- {
1740
- control,
1741
- name: "auto_sync_products",
1742
- render: ({ field: { value, onChange } }) => /* @__PURE__ */ jsx(Switch, { checked: value, onCheckedChange: onChange })
1743
- }
1744
- )
1745
- ] }),
1746
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1747
- /* @__PURE__ */ jsx(Label, { children: "Sync Orders" }),
1748
- /* @__PURE__ */ jsx(
1749
- Controller,
1750
- {
1751
- control,
1752
- name: "auto_sync_orders",
1753
- render: ({ field: { value, onChange } }) => /* @__PURE__ */ jsx(Switch, { checked: value, onCheckedChange: onChange })
1754
- }
1755
- )
1756
- ] })
1757
- ] }),
1758
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
1759
- /* @__PURE__ */ jsx(Text, { weight: "plus", children: "Reverse Sync (QuickBooks to Medusa)" }),
1760
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-subtle text-small", children: "Requires Webhooks to be configured in QuickBooks." }),
1761
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1762
- /* @__PURE__ */ jsx(Label, { children: "Sync Customers (Recieve Updates)" }),
1763
- /* @__PURE__ */ jsx(
1764
- Controller,
1765
- {
1766
- control,
1767
- name: "reverse_sync_customers",
1768
- render: ({ field: { value, onChange } }) => /* @__PURE__ */ jsx(Switch, { checked: value, onCheckedChange: onChange })
1769
- }
1770
- )
1771
- ] }),
1772
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1773
- /* @__PURE__ */ jsx(Label, { children: "Sync Products (Receive Updates)" }),
1774
- /* @__PURE__ */ jsx(
1775
- Controller,
1776
- {
1777
- control,
1778
- name: "reverse_sync_products",
1779
- render: ({ field: { value, onChange } }) => /* @__PURE__ */ jsx(Switch, { checked: value, onCheckedChange: onChange })
1780
- }
1781
- )
1782
- ] })
1783
- ] })
1784
- ] })
1785
- ] }),
1786
- /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(Button, { type: "submit", isLoading: isSaving, children: "Save Settings" }) })
1787
- ] })
1788
- ] });
1789
- };
1790
- const config = defineRouteConfig({
1791
- label: "QuickBooks",
1792
- icon: "currency-dollar"
1793
- });
1794
- const i18nTranslations0 = {};
1795
- const widgetModule = { widgets: [] };
1796
- const routeModule = {
1797
- routes: [
1798
- {
1799
- Component: QuickBooksSettingsPage,
1800
- path: "/settings/quickbooks"
1801
- }
1802
- ]
1803
- };
1804
- const menuItemModule = {
1805
- menuItems: [
1806
- {
1807
- label: config.label,
1808
- icon: config.icon,
1809
- path: "/settings/quickbooks",
1810
- nested: void 0,
1811
- rank: void 0,
1812
- translationNs: void 0
1813
- }
1814
- ]
1815
- };
1816
- const formModule = { customFields: {} };
1817
- const displayModule = {
1818
- displays: {}
1819
- };
1820
- const i18nModule = { resources: i18nTranslations0 };
1821
- const plugin = {
1822
- widgetModule,
1823
- routeModule,
1824
- menuItemModule,
1825
- formModule,
1826
- displayModule,
1827
- i18nModule
1828
- };
1829
- export {
1830
- plugin as default
1831
- };
1
+ // Medusa Admin Extension Entry Point
2
+ // Must export 'widgets' and 'default' to be valid for the dashboard loader.
3
+ export const widgets = [];
4
+ const plugin = { widgets };
5
+ export default plugin;