-
Notifications
You must be signed in to change notification settings - Fork 206
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Update vendor dashboard structure convert withdraw #2506
base: develop
Are you sure you want to change the base?
Update vendor dashboard structure convert withdraw #2506
Conversation
This commit introduces a new REST API endpoint for searching customers specific to a vendor's orders. Key changes include: - Add new route `/dokan/v1/customers/search` in CustomersController - Implement `search_customers` method with the following features: * Search customers by ID or term (name/email) * Limit results to customers who have ordered from the current vendor * Support excluding specific customer IDs * Limit results to 20 when search term is less than 3 characters * Apply `dokan_json_search_found_customers` filter for extensibility - Add permission check to ensure only users with 'edit_shop_orders' capability can access - Include detailed PHPDoc for the new filter This feature allows vendors to efficiently search their customer base through the REST API, mirroring the functionality of the existing AJAX action while providing a standardized API interface.
…ure' into update/vendor-dashboard-structure
…e' into update/vendor-dashboard-structure
…ses for Customer API
…er-api' into update/vendor-dashboard-structure # Conflicts: # includes/REST/Manager.php
…shboard-structure
# Conflicts: # includes/REST/Manager.php
# Conflicts: # composer.lock
# Conflicts: # composer.lock
…ure-convert-withdraw # Conflicts: # composer.lock
…emplate override conditions (#2443) * feat: Template detection for react menu rendering * doc: How to define a menu is available in `React` and its `PHP` override information. * doc: Table of content added * refactor: code review suggestion implemented
…e' into update/vendor-dashboard-structure # Conflicts: # composer.lock
…e' into update/vendor-dashboard-structure
…e' into update/vendor-dashboard-structure
…ion. (#2484) * enhance: Split dokan rest controller class for role-wise API implementation. * fix: Update rest base for admin, vendor, customer controllers. * fix: api documentation for admin controller usecase. * fix: update base api class name `DokanBaseRESTController` to `DokanRESTBaseController`, remove redunded properties, update api docs.
…ate/vendor-dashboard-structure
…andle responsive preview from base components.
…ce-dataviews-from-dokan-free
…te/vendor-dashboard-structure-convert-withdraw # Conflicts: # package-lock.json
…ataviews-from-dokan-free' into update/vendor-dashboard-structure-convert-withdraw # Conflicts: # includes/Assets.php # package.json
…& add documentation for components, utilities.
… into update/vendor-dashboard-structure-convert-withdraw # Conflicts: # src/hooks/useCurrentUser.ts
WalkthroughThis pull request introduces a comprehensive set of changes to the Dokan plugin, focusing on enhancing the frontend architecture, adding new REST API controllers, implementing React components for withdrawal management, and introducing a Tailwind CSS configuration. The changes span multiple areas including routing, component design, API endpoints, and styling, with a significant emphasis on improving the vendor dashboard and withdrawal-related functionalities. Changes
Sequence DiagramsequenceDiagram
participant User
participant Dashboard
participant WithdrawAPI
participant PaymentMethods
User->>Dashboard: Navigates to Withdraw
Dashboard->>WithdrawAPI: Fetch Balance
WithdrawAPI-->>Dashboard: Return Balance Data
Dashboard->>WithdrawAPI: Fetch Withdrawal Settings
WithdrawAPI-->>Dashboard: Return Payment Methods
Dashboard->>PaymentMethods: Render Available Methods
User->>PaymentMethods: Select Default Method
PaymentMethods->>WithdrawAPI: Set Default Method
WithdrawAPI-->>PaymentMethods: Confirm Method Update
Possibly related PRs
Suggested Labels
Suggested Reviewers
Poem
Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 37
🔭 Outside diff range comments (1)
includes/Assets.php (1)
Line range hint
392-605
: Check Compatibility with WooCommerce VersionsThe use of
WCAdminAssets::get_instance()
may cause compatibility issues with older versions of WooCommerce that do not have this class. To prevent potential fatal errors, consider adding a check to ensure that the class exists before calling its methods.Apply this diff to prevent compatibility issues:
+ if ( class_exists( 'Automattic\WooCommerce\Internal\Admin\WCAdminAssets' ) ) { $wc_instance = WCAdminAssets::get_instance(); $wc_instance->register_scripts(); + }Also, consider specifying the minimum WooCommerce version required for your plugin.
🧹 Nitpick comments (81)
src/Definitions/CountryState.ts (4)
1-5
: API documentation needs improvement.The API endpoint example uses a placeholder domain (
you-site.test
) which should be replaced with proper documentation.-* Api is: http://you-site.test/wp-json/dokan/v1/data/countries +* API endpoint: /wp-json/dokan/v1/data/countries +* +* @since 1.0.0 +* @see DokanDataCountriesController
7-14
: Add JSDoc comments for better documentation.The Link and Links interfaces would benefit from JSDoc comments explaining their purpose and relationship to the HAL specification.
+/** + * Represents a HAL-compliant hyperlink. + * @see https://tools.ietf.org/html/draft-kelly-json-hal + */ export interface Link { href: string; } +/** + * Collection of HAL-compliant hyperlinks for API navigation. + */ export interface Links { self: Link[]; collection: Link[]; }
16-26
: Consider adding optional fields to State interface.The State interface could be more comprehensive by including optional fields that might be useful for address formatting or validation.
export interface State { code: string; name: string; + country_code?: string; + is_active?: boolean; }
30-34
: Consider using a specific error type.Instead of using a generic string for errors, consider creating a specific error type to better handle different error cases.
+export type CountryStateError = { + message: string; + code?: string; + details?: unknown; +} export interface CountryStateState { countries: Record<string, Country>; isLoading: Record<string, boolean>; - errors: Record<string, string | null>; + errors: Record<string, CountryStateError | null>; }src/Definitions/Continents.ts (1)
4-15
: Enhance Country interface with validation constraints.The Country interface could benefit from more specific type constraints and documentation.
+/** + * Represents a country with its currency and measurement settings. + */ export interface Country { code: string; + /** ISO 3166-1 alpha-2 country code */ name: string; + /** ISO 4217 currency code */ currency_code: string; currency_pos: 'left' | 'right' | 'left_space' | 'right_space'; decimal_sep: string; dimension_unit: 'cm' | 'foot'; - num_decimals: number; + num_decimals: number & { __brand: 'NonNegativeInteger' }; thousand_sep: string; weight_unit: 'kg' | 'oz'; states: State[]; }includes/REST/DokanDataCountriesController.php (3)
7-8
: Remove Unused ImportsThe imported classes
WP_Error
,WP_REST_Request
, andWP_REST_Response
are not used in the code. Removing unused imports improves code clarity.Apply this diff to remove unused imports:
-use WP_Error; -use WP_REST_Request; -use WP_REST_Response;
80-83
: Replace Placeholder Constants in DocBlocksThe
@since DOKAN_SINCE
annotation contains a placeholder. Replace it with the actual version number for accurate documentation.Apply this diff:
- * @since DOKAN_SINCE + * @since 3.5.0
91-98
: Inconsistent Error Codes and Text DomainsThe error code
'dokan_pro_permission_failure'
and text domain'dokan-lite'
might not reflect the correct plugin context. Ensure consistency in error handling.Apply this diff:
- 'dokan_pro_permission_failure', - __( 'You are not allowed to do this action.', 'dokan-lite' ), + 'dokan_permission_failure', + __( 'You are not allowed to perform this action.', 'dokan' ),includes/REST/DokanDataContinentsController.php (4)
7-8
: Remove Unused ImportsThe imported classes
WP_Error
,WP_REST_Request
, andWP_REST_Response
are not utilized. Cleaning them up enhances code readability.Apply this diff:
-use WP_Error; -use WP_REST_Request; -use WP_REST_Response;
80-83
: Replace Placeholder Constants in DocBlocksUpdate
@since DOKAN_SINCE
with the actual version number for accurate documentation.Apply this diff:
- * @since DOKAN_SINCE + * @since 3.5.0
91-98
: Inconsistent Error Codes and Text DomainsThe error code
'dokan_pro_permission_failure'
and text domain'dokan-lite'
may not be consistent with the plugin's context. Ensure they accurately reflect the usage.Apply this diff:
- 'dokan_pro_permission_failure', - __( 'You are not allowed to do this action.', 'dokan-lite' ), + 'dokan_permission_failure', + __( 'You are not allowed to perform this action.', 'dokan' ),
48-54
: Incorrect Method DocumentationThe
get_item
method documentation mentions returning states for a country, but in the context of continents, this should be corrected.Apply this diff:
- * Return the list of states for a given country. + * Return the data for a given continent.includes/VendorNavMenuChecker.php (3)
13-13
: Typographical Error in DocBlockThere is a missing asterisk in the DocBlock for the
$template_dependencies
property.Apply this diff:
- [ 'route' => [ ['slug' => 'template-slug', 'name' => 'template-name' (Optional), 'args' = [] (Optional) ] ] ] + * [ 'route' => [ ['slug' => 'template-slug', 'name' => 'template-name' (Optional), 'args' => [] (Optional) ] ] ]
70-77
: Simplify Boolean LogicThe logic in
is_dependency_cleared
can be simplified to improve readability.Apply this diff:
- $clear = true; - $dependencies = $this->get_template_dependencies_resolutions(); - - if ( ! empty( $dependencies[ trim( $route, '/' ) ] ) ) { - $clear = false; - } + $dependencies = $this->get_template_dependencies_resolutions(); + $clear = empty( $dependencies[ trim( $route, '/' ) ] );
201-204
: Correct Internationalization Function UsageThe translation function should properly wrap the entire message, including the placeholders.
Apply this diff:
- $notice = sprintf( - /* translators: %s: overridden templates */ - __( 'The following templates are overridden:<br><code>%s</code>', 'dokan-lite' ), - implode( ',<br>', $overridden_templates ) - ); + /* translators: %s: overridden templates */ + $notice = sprintf( + __( 'The following templates are overridden:<br><code>%s</code>', 'dokan-lite' ), + implode( ',<br>', $overridden_templates ) + );includes/REST/CustomersController.php (1)
232-242
: Replace Placeholder@since DOKAN_SINCE
with Actual VersionIn the docblock for the
dokan_json_search_found_customers
filter, the@since
tag usesDOKAN_SINCE
as a placeholder. Please replaceDOKAN_SINCE
with the actual version number when this code is released to maintain accurate documentation.includes/Assets.php (2)
19-23
: Ensure Proper Escaping of Output inwp_footer
ActionIn the
wp_footer
action, raw HTML is echoed directly. While the content is static, it's good practice to use proper escaping functions to enhance security and maintainability.Apply this diff to escape the output:
add_action( 'wp_footer', function () { - echo '<div class="dokan-layout" id="headlessui-portal-root"><div></div></div>'; + echo '<div class="dokan-layout" id="headlessui-portal-root"><div></div></div>'; } );Alternatively, since the HTML is static and controlled, you might consider leaving it as is but be cautious with any dynamic content.
918-918
: Avoid Global Namespace Pollution inwp_localize_script
When localizing the script
dokan-react-frontend
, the variable namedokanCurrency
is added to the global scope. To prevent potential conflicts, consider namespacing it within an existing global object likedokan
.Modify the code as follows:
- wp_localize_script( 'dokan-react-frontend', 'dokanCurrency', $this->get_localized_price() ); + wp_localize_script( 'dokan-react-frontend', 'dokan', array_merge( isset( $dokan ) ? $dokan : [], [ 'currency' => $this->get_localized_price() ] ) );Then, in your JavaScript, access it using
dokan.currency
.src/layout/404.tsx (2)
1-9
: Add Type Annotation to Functional ComponentTo improve type safety and maintainability in TypeScript, it's recommended to add type annotations to your components. Consider specifying the type for the
NotFound
component.Apply this diff to add the type annotation:
const NotFound = () => { +// or +const NotFound: React.FC = () => {
1-9
: Enhance the 404 Page User ExperienceThe current
NotFound
component displays a simple message. Consider enhancing the user experience by adding navigation options, such as a link to the homepage or a search bar, to help users find what they're looking for.Example:
return ( <div> - <h1>404 - Not Found!</h1> + <h1>404 - Page Not Found</h1> + <p>The page you are looking for does not exist.</p> + <a href="/">Go to Homepage</a> </div> );src/Definitions/RouterProps.ts (2)
13-13
: Consider replacingany
with a more specific type.Using
any
reduces type safety. Consider defining an interface for the location state or useunknown
if the state type is truly unpredictable.- location: Location< any >; + location: Location< unknown >;
16-16
: Consider adding more specific types for UIMatch generics.The
unknown
type parameters could be replaced with more specific types based on your route configuration.- matches: UIMatch< unknown, unknown >[]; + matches: UIMatch< object, string >[]; // Adjust based on your actual route params and datasrc/layout/ContentArea.tsx (2)
4-15
: Add TypeScript type definitions to improve maintainability.The component could benefit from TypeScript types for better maintainability and developer experience.
-const ContentArea = ( { children } ) => { +interface ContentAreaProps { + children: React.ReactNode; +} + +const ContentArea: React.FC<ContentAreaProps> = ({ children }) => {
8-12
: Consider extracting slot names as constants.The slot names could be extracted as constants to prevent typos and enable reuse.
+const CONTENT_AREA_SLOTS = { + BEFORE: 'dokan-layout-content-area-before', + AFTER: 'dokan-layout-content-area-after', +} as const; + <div className="dokan-layout-content-area"> - <Slot name="dokan-layout-content-area-before" /> + <Slot name={CONTENT_AREA_SLOTS.BEFORE} /> { children } - <Slot name="dokan-layout-content-area-after" /> + <Slot name={CONTENT_AREA_SLOTS.AFTER} /> </div>src/Components/DokanTooltip.tsx (1)
14-14
: Consider extracting Tailwind classes to a constant or using a CSS module.Hardcoded CSS classes could be made more maintainable by extracting them to a constant or using a CSS module.
+const TOOLTIP_CLASSES = 'block text-sm text-gray-500 mb-1' as const; + <div - className="block text-sm text-gray-500 mb-1" + className={TOOLTIP_CLASSES}src/layout/Header.tsx (2)
4-4
: Add TypeScript type definition for propsConsider adding explicit type definition for the component props to improve type safety.
-const Header = ( { title = '' } ) => { +type HeaderProps = { + title?: string; +}; + +const Header = ( { title = '' }: HeaderProps ) => {
11-11
: Consider accessibility improvements for the headingThe h1 heading level might not be appropriate in all contexts where this component is used. Consider making the heading level configurable.
-{ title && (<h1 className="mb-4 text-3xl font-semibold text-gray-800 dark:text-white md:text-4xl lg:text-4xl">{title}</h1>)} +{ title && ( + <Heading + level={headingLevel} + className="mb-4 text-3xl font-semibold text-gray-800 dark:text-white md:text-4xl lg:text-4xl" + > + {title} + </Heading> +)}src/Definitions/window-types.ts (2)
18-18
: Replaceany
type with more specific type definitionUsing
any
type reduces TypeScript's type safety benefits. Consider using a more specific return type for the moment function.-moment: ( date: string ) => any; +moment: ( date: string ) => moment.Moment;
30-31
: Remove unnecessary empty exportThe empty export statement is flagged as unnecessary by the static analysis tool since there are already imports present.
-// This empty export is necessary to make this a module -export {};🧰 Tools
🪛 Biome (1.9.4)
[error] 30-31: This empty export is useless because there's another export or import.
This import makes useless the empty export.
Safe fix: Remove this useless empty export.
(lint/complexity/noUselessEmptyExport)
src/dashboard/index.tsx (1)
11-27
: Consider memoizing mapped routesThe routes mapping could be memoized to prevent unnecessary re-renders.
+import { useMemo } from 'react'; const App = () => { const routes = getRoutes(); - const mapedRoutes = routes.map((route) => { + const mappedRoutes = useMemo(() => routes.map((route) => { const WithRouterComponent = withRouter(route.element); return { path: route.path, element: ( <Layout headerComponent={route?.header} footerComponent={route?.footer} route={route} title={route?.title} > <WithRouterComponent /> </Layout> ), }; - }); + }), [routes]);src/Components/PriceHtml.tsx (1)
15-22
: Simplify default value assignmentsThe multiple if statements for default values can be simplified using object destructuring with default values.
-const PriceHtml = ( { - price = 0, - currencySymbol = '', - precision = null, - thousand = '', - decimal = '', - format = '', -}: PriceHtmlProps ) => { - if ( ! currencySymbol ) { - currencySymbol = window.dokanCurrency.symbol; - } - if ( ! precision ) { - precision = window.dokanCurrency.precision; - } - if ( ! thousand ) { - thousand = window.dokanCurrency.thousand; - } - if ( ! decimal ) { - decimal = window.dokanCurrency.decimal; - } - if ( ! format ) { - format = window.dokanCurrency.format; - } +const PriceHtml = ({ + price = 0, + currencySymbol = window.dokanCurrency.symbol, + precision = window.dokanCurrency.precision, + thousand = window.dokanCurrency.thousand, + decimal = window.dokanCurrency.decimal, + format = window.dokanCurrency.format, +}: PriceHtmlProps) => {src/hooks/ViewportDimensions.ts (2)
11-11
: Update version placeholderThe
@since
tag contains a placeholderDOKAN_PRO_SINCE
. This should be replaced with the actual version number.
16-19
: Consider memoizing viewport dimensions objectThe viewport dimensions object is recreated on every render. Consider memoizing it with
useMemo
for better performance.- const getViewportDimensions = useCallback((): ViewportDimensions => ({ + const getViewportDimensions = useCallback((): ViewportDimensions => { + if (typeof window === 'undefined') { + return { width: null, height: null }; + } + return { width: typeof window !== 'undefined' ? window.innerWidth : null, height: typeof window !== 'undefined' ? window.innerHeight : null, - }), []); + }; + }, []);src/Components/DateTimeHtml.tsx (1)
26-65
: Reduce code duplication in static methodsThe
Date
andTime
static methods contain similar logic. Consider extracting the common functionality into a shared utility function.const formatDateTime = ( value: string, format: string, defaultValue: string | JSX.Element | null = '-' ) => { if (!value) { return defaultValue; } return ( <RawHTML> {dateI18n(format, value, getSettings().timezone.string)} </RawHTML> ); };src/Dashboard/Withdraw/Hooks/useCharge.ts (1)
27-51
: Consider implementing debouncingThe
fetchCharge
function could benefit from debouncing to prevent excessive API calls when amount changes frequently.Consider using the
lodash/debounce
utility:import { debounce } from 'lodash'; const debouncedFetch = useCallback( debounce(async (method: string, amount: string) => { // existing fetch logic }, 300), [] );includes/REST/OrderControllerV3.php (1)
12-12
: Replace placeholder with actual version numberThe
@since DOKAN_SINCE
placeholder should be replaced with the actual version number.src/Dashboard/Withdraw/Hooks/useWithdrawSettings.ts (1)
36-57
: Add retry mechanism for failed requestsConsider implementing a retry mechanism for failed API requests, especially for network-related errors.
const fetchSettings = useCallback( async () => { + const MAX_RETRIES = 3; + let retries = 0; + + const attemptFetch = async (): Promise<WithdrawSettings> => { try { - setIsLoading( true ); - setError( null ); - - const response = await apiFetch< WithdrawSettings >( { + return await apiFetch< WithdrawSettings >( { path: '/dokan/v2/withdraw/settings', method: 'GET', } ); - - setData( response ); } catch ( err ) { + if (retries < MAX_RETRIES && err instanceof Error && err.message.includes('network')) { + retries++; + await new Promise(resolve => setTimeout(resolve, 1000 * retries)); + return attemptFetch(); + } + throw err; + } + }; + + try { + setIsLoading(true); + setError(null); + const response = await attemptFetch(); + setData(response); + } catch (err) { setError( err instanceof Error ? err : new Error( 'Failed to fetch withdraw settings' ) ); console.error( 'Error fetching withdraw settings:', err ); - } finally { - setIsLoading( false ); - } + } finally { + setIsLoading(false); + } }, [] );src/hooks/useCurrentUser.ts (2)
17-17
: Improve type safety for meta fieldUsing
any[]
for meta reduces type safety. Consider defining a proper interface for the meta structure.- meta: any[]; + meta: { + key: string; + value: string | number | boolean; + }[];
62-64
: Remove or document commented codeThe commented useEffect suggests automatic data fetching was considered but disabled. Either remove it or document why it's kept as a reference.
- // useEffect( () => { - // fetchCurrentUser(); - // }, [ fetchCurrentUser ] );src/layout/index.tsx (2)
11-12
: Consider adding type safety to ThemeContextThe context is created with
null
as initial value without type definitions. This could lead to runtime type errors.-const ThemeContext = createContext( null ); +type ThemeContextType = { + theme: string; + setTheme: (theme: string) => void; +}; +const ThemeContext = createContext<ThemeContextType | null>(null);
46-71
: Consider adding error boundary and loading statesThe Layout component looks good but could benefit from error handling and loading states for better user experience.
Consider wrapping the content with an error boundary:
+import { ErrorBoundary } from '@wordpress/element'; + const Layout = ({ children, ...props }: LayoutProps) => { return ( <ThemeProvider> <SlotFillProvider> + <ErrorBoundary fallback={<div>Something went wrong.</div>}> <div className="dokan-layout"> {/* ... existing code ... */} </div> + </ErrorBoundary> <PluginArea scope={route.id} /> <DokanToaster /> </SlotFillProvider> </ThemeProvider> ); };src/Dashboard/Withdraw/index.tsx (1)
33-65
: Consider memoizing child components to prevent unnecessary re-rendersThe child components receive new object references on every render which could cause performance issues.
+const memoizedBalance = useMemo(() => ( <Balance masterLoading={currentUser.isLoading || useWithdrawRequestHook.isLoading} bodyData={balance} settings={withdrawSettings} withdrawRequests={useWithdrawRequestHook} /> +), [currentUser.isLoading, useWithdrawRequestHook.isLoading, balance, withdrawSettings]);src/Dashboard/Withdraw/Hooks/useWithdraw.ts (1)
31-35
: Add request cancellation handlingThe API requests should be cancellable when the component unmounts.
+import { addQueryArgs } from '@wordpress/url'; const createWithdraw = useCallback( async (payload: WithdrawPayload): Promise<void> => { + const abortController = new AbortController(); try { setIsLoading(true); setError(null); await apiFetch({ path: '/dokan/v1/withdraw', method: 'POST', data: payload, + signal: abortController.signal, }); + return () => abortController.abort(); } catch (err) { + if (err.name === 'AbortError') { + return; + } // ... rest of error handling } }, [] );src/Routing/index.tsx (1)
46-77
: Refactor route definitions for better maintainability.The current implementation adds routes individually with repeated code. Consider refactoring to use a route configuration array.
Here's a suggested refactor:
const getRoutes = () => { - let routes : Array<DokanRoute> = []; + const routeConfigs: Array<DokanRoute> = [ + { + id: 'dokan-base', + title: __( 'Dashboard', 'dokan-lite' ), + element: <h1>Dashboard body</h1>, + path: '/', + exact: true, + order: 10, + }, + { + id: 'dokan-withdraw', + title: __( 'Withdraw', 'dokan-lite' ), + element: <Withdraw/>, + path: '/withdraw', + exact: true, + order: 10, + }, + { + id: 'dokan-withdraw-requests', + title: __( 'Withdraw', 'dokan-lite' ), + element: <WithdrawRequests/>, + path: '/withdraw-requests', + exact: true, + order: 10, + }, + ]; + + let routes = [...routeConfigs];src/Components/DataTable.tsx (2)
35-37
: Improve click handler with optional chaining.The click handler can be simplified using optional chaining for better readability and safety.
Apply this diff:
- onClick={() => { - onRowClick && onRowClick(row.original); - }} + onClick={() => onRowClick?.(row.original)}🧰 Tools
🪛 Biome (1.9.4)
[error] 36-36: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
9-61
: Consider adding loading and empty states.The table handles data well but doesn't provide feedback for loading or empty states. This could impact user experience.
Consider adding:
- A loading spinner or skeleton for loading state
- A meaningful message when there's no data
🧰 Tools
🪛 Biome (1.9.4)
[error] 36-36: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
src/Definitions/woocommerce-accounting.d.ts (2)
81-86
: Improve type safety of helper methods.The helper methods use the
any
type, which reduces type safety. Consider using more specific types.Apply this diff:
- isNumber(value: any): boolean; - isArray(value: any): boolean; - isObject(value: any): boolean; - isString(value: any): boolean; - isFunction(value: any): boolean; - isDefined(value: any): boolean; + isNumber(value: unknown): value is number; + isArray(value: unknown): value is Array<unknown>; + isObject(value: unknown): value is Record<string, unknown>; + isString(value: unknown): value is string; + isFunction(value: unknown): value is Function; + isDefined<T>(value: T | undefined | null): value is T;
2-17
: Add JSDoc comments for better documentation.The interfaces would benefit from JSDoc comments explaining their purpose and usage.
Consider adding JSDoc comments like this:
/** Settings interface for WooCommerce accounting configuration */ interface Settings { /** Currency-specific settings */ currency: { // ... (existing properties with comments) }; /** Number formatting settings */ number: { // ... (existing properties with comments) }; }Also applies to: 19-30, 32-110
src/Definitions/Order.ts (2)
37-37
: Consider using more specific types instead ofany[]
Replace
any[]
with more specific types to improve type safety. This applies to:
taxes
arrays inLineItem
andShippingLine
tax_lines
,fee_lines
, andrefunds
arrays inOrder
Example for tax lines:
interface TaxLine { id: number; rate_code: string; rate_id: number; label: string; compound: boolean; tax_total: string; shipping_tax_total: string; }Also applies to: 51-51, 124-127
76-85
: Consider removing the catch-all string from OrderStatusThe
OrderStatus
type includes a catch-allstring
which defeats the purpose of having a specific union type. Consider removing it if these are all the valid statuses.export type OrderStatus = | 'pending' | 'processing' | 'on-hold' | 'completed' | 'cancelled' | 'refunded' | 'failed' - | 'trash' - | string; + | 'trash';src/Dashboard/Withdraw/Balance.tsx (2)
50-51
: Remove unnecessary fragmentThe fragment wrapper is unnecessary since there's only one child element.
- return ( - <> <Card className="dokan-withdraw-style-reset dokan-layout"> - </> - ); + return ( + <Card className="dokan-withdraw-style-reset dokan-layout"> + );Also applies to: 96-97
65-68
: Simplify optional chainingThe optional chaining with nullish coalescing can be simplified.
-price={ - bodyData?.data?.current_balance ?? - '' -} +price={bodyData?.data?.current_balance ?? ''} -price={ - bodyData?.data?.withdraw_limit ?? '' -} +price={bodyData?.data?.withdraw_limit ?? ''}Also applies to: 82-84
src/Dashboard/Withdraw/Hooks/useWithdrawRequests.ts (1)
94-101
: Define a custom error type for better error handlingCreate a custom error type to handle specific withdraw request errors.
interface WithdrawRequestError extends Error { code?: string; details?: string; } // Usage in catch block: } catch (err) { const error: WithdrawRequestError = err instanceof Error ? err : new Error('Failed to fetch withdraw requests'); setError(error); console.error('Error fetching withdraw requests:', error); }src/Components/Pagination.tsx (1)
5-12
: Props interface looks good, but could benefit from JSDoc documentation.The Props interface is well-structured with appropriate types. Consider adding JSDoc comments to document the purpose of each prop for better maintainability.
+/** + * Props for the Pagination component + * @template T - The type of data being paginated + */ type Props<T> = { + /** The table instance */ table: Table<T>; + /** Optional class name for the container */ className?: string; + /** Loading state of the pagination */ isLoading?: boolean; + /** Custom classes for pagination buttons */ btnClasses?: string; + /** Custom classes for text elements */ textClasses?: string; + /** Custom classes for the page input */ inputClasses?: string; };src/Definitions/Product.ts (1)
82-82
: Use string literals for enumerable values.Several properties that have a fixed set of possible values should use string literals for better type safety.
interface Product { // ... - type: string; - status: string; - catalog_visibility: string; - tax_status: string; - tax_class: string; + type: 'simple' | 'variable' | 'grouped' | 'external' | 'subscription'; + status: 'draft' | 'pending' | 'private' | 'publish'; + catalog_visibility: 'visible' | 'catalog' | 'search' | 'hidden'; + tax_status: 'taxable' | 'shipping' | 'none'; + tax_class: 'standard' | 'reduced-rate' | 'zero-rate'; // ... }Also applies to: 83-83, 85-85, 86-86, 107-107, 108-108
base-tailwind.config.js (1)
18-19
: Consider adding opacity variants for background colors.The background colors could benefit from opacity variants for more flexible styling options.
backgroundColor: { dokan: { sidebar: { - DEFAULT: 'var(--dokan-sidebar-background-color, #F05025)', - hover: 'var(--dokan-sidebar-hover-background-color, #F05025)', + DEFAULT: 'rgb(var(--dokan-sidebar-background-color-rgb, 240 80 37) / <alpha-value>)', + hover: 'rgb(var(--dokan-sidebar-hover-background-color-rgb, 240 80 37) / <alpha-value>)', }, btn: { - DEFAULT: 'var(--dokan-button-background-color, #F05025)', - hover: 'var(--dokan-button-hover-background-color, #F05025)', + DEFAULT: 'rgb(var(--dokan-button-background-color-rgb, 240 80 37) / <alpha-value>)', + hover: 'rgb(var(--dokan-button-hover-background-color-rgb, 240 80 37) / <alpha-value>)', }, }, },Also applies to: 23-24
src/Dashboard/Withdraw/TableSkeleton.tsx (1)
34-61
: Make the number of skeleton rows configurable.The number of skeleton rows is hardcoded to 10. Consider making this configurable through props for better reusability.
+interface TableSkeletonProps { + rowCount?: number; +} -const TableSkeleton = () => { +const TableSkeleton = ({ rowCount = 10 }: TableSkeletonProps) => { // ... - { [ ...Array( 10 ) ].map( ( _, index ) => ( + { [ ...Array( rowCount ) ].map( ( _, index ) => (includes/REST/WithdrawControllerV2.php (2)
76-107
: Consider caching the mapped arrays for better performance.The method performs array mapping operations twice. Consider caching the results to avoid redundant operations.
public function get_withdraw_settings() { $active_methods = dokan_withdraw_get_withdrawable_active_methods(); $payment_methods = array_intersect( dokan_get_seller_active_withdraw_methods(), dokan_withdraw_get_active_methods() ); $default_withdraw_method = dokan_withdraw_get_default_method( dokan_get_current_user_id() ); $setup_url = dokan_get_navigation_url( 'settings/payment' ); + $mapped_payment_methods = array_map( + function ( $payment_method ) { + return [ + 'label' => dokan_withdraw_get_method_title( $payment_method ), + 'value' => $payment_method, + ]; + }, $payment_methods + ); + + $mapped_active_methods = array_map( + function ( $active_method ) { + return [ + 'label' => dokan_withdraw_get_method_title( $active_method ), + 'value' => $active_method, + 'icon' => dokan_withdraw_get_method_icon( $active_method ), + 'info' => dokan_withdraw_get_method_additional_info( $active_method ), + 'has_information' => in_array( $active_method, dokan_get_seller_active_withdraw_methods(), true ), + ]; + }, $active_methods + ); return rest_ensure_response( [ 'withdraw_method' => $default_withdraw_method, - 'payment_methods' => $payment_methods, - 'active_methods' => $active_methods, + 'payment_methods' => $mapped_payment_methods, + 'active_methods' => $mapped_active_methods, 'setup_url' => $setup_url, ] );
124-148
: Add success status code constant.The success status code should use the WP_REST_Response status code constant for consistency.
- return new WP_REST_Response( __( 'Default method update successful.', 'dokan-lite' ), 200 ); + return new WP_REST_Response( + __( 'Default method update successful.', 'dokan-lite' ), + WP_REST_Response::HTTP_OK + );src/Dashboard/Withdraw/WithdrawRequests.tsx (2)
53-53
: Consider adding error boundary.The component handles loading states but lacks error boundaries for error handling.
+import { ErrorBoundary } from '@getdokan/dokan-ui'; + function WithdrawRequests() { // ... existing code ... return ( + <ErrorBoundary> <SlotFillProvider> {/* existing code */} </SlotFillProvider> + </ErrorBoundary> ); }
41-55
: Add debounce to prevent excessive API calls.The effect hook might trigger multiple API calls when location.search or currentUser.data changes rapidly.
+import { useDebounce } from '@getdokan/dokan-ui'; + useEffect(() => { + const debouncedFetch = useDebounce(() => { useWithdrawRequestHook.fetchWithdrawRequests({ per_page: useWithdrawRequestHook?.view?.perPage, page, status, user_id: 1, }); + }, 300); + + debouncedFetch(); + + return () => { + debouncedFetch.cancel(); + }; }, [location.search, currentUser?.data]);src/Dashboard/Withdraw/PaymentDetails.tsx (1)
125-144
: Add empty state handling.The component should display a message when there are no pending requests.
{ !withdrawRequests?.isLoading && withdrawRequests?.data && Array.isArray(withdrawRequests?.data) && - withdrawRequests?.data.length > 0 && ( + (withdrawRequests?.data.length > 0 ? ( <div className="flex flex-col border-t pt-4"> <h4 className="font-medium text-gray-900 mb-2"> {__('Pending Requests', 'dokan')} </h4> <RequestList withdrawRequests={withdrawRequests} status="pending" loading={masterLoading || withdrawRequests.isLoading || settings.isLoading} /> </div> + ) : ( + <p className="text-gray-600"> + {__('No pending withdrawal requests.', 'dokan')} + </p> + )) }src/Dashboard/Withdraw/PaymentMethods.tsx (1)
56-108
: Consider simplifying conditional logic and using router navigation.The actionButton function could be improved in two ways:
- The nested conditionals could be flattened using early returns for better readability
- Direct window.location.href usage could be replaced with React Router for better SPA navigation
Consider refactoring to:
const actionButton = (activemethod: WithdrawMethod) => { - if (activemethod.has_information && activemethod?.value === bodyData?.data?.withdraw_method) { + if (!activemethod.has_information) { + return ( + <Button + type="button" + color="secondary" + className="bg-dokan-btn hover:bg-dokan-btn-hover text-white" + onClick={() => navigate(bodyData?.data?.setup_url)} + label={__('Setup', 'dokan-lite')} + /> + ); + } + + if (activemethod?.value === bodyData?.data?.withdraw_method) { return ( <Button color="secondary" className="bg-gray-50 hover:bg-gray-100" disabled={true} label={__('Default', 'dokan-lite')} /> ); - } else if (activemethod.has_information && activemethod?.value !== bodyData?.data?.withdraw_method) { + } + + return ( // ... rest of the code - } - return ( - // ... setup button code - ); };includes/REST/Manager.php (1)
204-207
: Clean addition of new REST controllers!The new controllers are properly mapped following the existing pattern. However, consider adding version numbers to the controller classes for better API versioning control, similar to how OrderControllerV3 is named.
Consider renaming the new controllers to include version numbers:
-DOKAN_DIR . '/includes/REST/CustomersController.php' => '\WeDevs\Dokan\REST\CustomersController', +DOKAN_DIR . '/includes/REST/CustomersControllerV1.php' => '\WeDevs\Dokan\REST\CustomersControllerV1', -DOKAN_DIR . '/includes/REST/DokanDataCountriesController.php' => '\WeDevs\Dokan\REST\DokanDataCountriesController', +DOKAN_DIR . '/includes/REST/DokanDataCountriesControllerV1.php' => '\WeDevs\Dokan\REST\DokanDataCountriesControllerV1',src/Dashboard/Withdraw/RequestList.tsx (3)
33-38
: Consider memoizing the hasWithdrawRequests calculation.The hasWithdrawRequests check could be memoized using useMemo to avoid unnecessary recalculations on every render.
+import { useMemo } from '@wordpress/element'; -const hasWithdrawRequests = - withdrawRequests?.data && - Array.isArray( withdrawRequests?.data ) && - withdrawRequests?.data?.length > 0; +const hasWithdrawRequests = useMemo(() => + withdrawRequests?.data && + Array.isArray( withdrawRequests?.data ) && + withdrawRequests?.data?.length > 0, + [withdrawRequests?.data] +);
185-206
: Enhance error handling in cancellation flow.While the basic error handling is in place, consider adding more specific error messages and recovery options.
.catch(() => { toast({ type: 'error', - title: __('Failed to cancel request', 'dokan'), + title: __('Failed to cancel request. Please try again later.', 'dokan'), + description: __('If the problem persists, please contact support.', 'dokan'), + duration: 5000, }); })
248-286
: Consider extracting the confirmation modal into a separate component.The modal logic could be extracted into a reusable ConfirmationModal component to improve code organization and reusability.
Consider creating a new component:
interface ConfirmationModalProps { isOpen: boolean; onClose: () => void; onConfirm: () => void; isLoading: boolean; title: string; message: string; } const ConfirmationModal: React.FC<ConfirmationModalProps> = ({ isOpen, onClose, onConfirm, isLoading, title, message, }) => { // Modal implementation };src/Dashboard/Withdraw/RequestWithdrawBtn.tsx (2)
38-74
: Consider using a dedicated number formatting library.The current implementation relies on the global window.accounting object. Consider using a dedicated number formatting library like Intl.NumberFormat or currency.js for better maintainability and type safety.
const formatNumber = (value: string | number): string => { if (value === '') { return value as string; } return new Intl.NumberFormat(locale, { minimumFractionDigits: window.dokanCurrency.precision, maximumFractionDigits: window.dokanCurrency.precision, }).format(Number(value)); };
112-139
: Improve error handling in withdrawal creation.The error handling could be more specific and provide better feedback to users.
.catch((err) => { + const errorMessage = err?.response?.data?.message + ?? err?.message + ?? __('Failed to create withdraw request. Please try again.', 'dokan'); toast({ - title: err?.message ?? __('Failed to create withdraw.', 'dokan'), + title: errorMessage, type: 'error', + duration: 5000, }); - console.error('Error creating withdraw:', err); + console.error('[Withdraw Request Error]:', { error: err, payload }); });src/Definitions/Customers.ts (1)
1-13
: Consider adding validation patterns for contact information.The
CustomerAddress
interface could benefit from more specific types or validation patterns for:
- Phone numbers (format validation)
- Postcodes (format validation)
- Email addresses (format validation)
+type PhoneNumber = string; // Consider regex validation +type PostCode = string; // Consider regex validation +type Email = string; // Consider regex validation export interface CustomerAddress { first_name: string; last_name: string; company: string; address_1: string; address_2: string; city: string; - postcode: string; + postcode: PostCode; country: string; state: string; email?: Email; - phone: string; + phone: PhoneNumber; }src/Dashboard/Withdraw/tailwind.scss (2)
1-1
: Fix typo in mixin name.The mixin name
windraw-reset
appears to be a typo. Should it bewithdraw-reset
?-@mixin windraw-reset { +@mixin withdraw-reset {
15-17
: Consider using CSS custom properties for fallback colors.The hardcoded fallback color
#F05025
should be defined as a CSS custom property for better maintainability.- background-color: var(--dokan-button-hover-color, #F05025); - border-color: var(--dokan-button-hover-background-color, #F05025); + background-color: var(--dokan-button-hover-color, var(--dokan-brand-color)); + border-color: var(--dokan-button-hover-background-color, var(--dokan-brand-color));docs/frontend/components.md (3)
15-16
: Replace placeholder with actual path example.The script assets path is using a placeholder. Consider providing a realistic example path to help developers understand the expected format.
-$script_assets = 'add_your_script_assets_path_here'; +$script_assets = 'build/vendor/assets.php';
58-62
: Add webpack configuration example for external plugins.The webpack configuration example could be enhanced with more details about external dependencies.
externals: { '@dokan/components': 'dokan.components', + // Add other Dokan dependencies + '@wordpress/components': 'wp.components', + '@wordpress/element': 'wp.element', ... },
68-82
: Add language specification to the file structure code block.The file structure code block should specify a language for better syntax highlighting.
-``` +```text |____ src/ |___ components/🧰 Tools
🪛 Markdownlint (0.37.0)
68-68: null
Fenced code blocks should have a language specified(MD040, fenced-code-language)
docs/frontend/utilities.md (2)
15-25
: Add language specification to the file structure code block.The file structure code block should specify a language for better syntax highlighting.
-``` +```text |____ src/ |___ utilities/🧰 Tools
🪛 Markdownlint (0.37.0)
15-15: null
Fenced code blocks should have a language specified(MD040, fenced-code-language)
Line range hint
628-639
: Add error handling to the filter application.The filter application code should include error handling for undefined hooks or namespaces.
const applyFiltersToTableElements = (namespace: string, elementName: string, element) => { + if (!namespace || !elementName) { + console.warn('Invalid namespace or element name provided to filter'); + return element; + } return wp.hooks.applyFilters( `${namespace}.${elementName}`, element ); };🧰 Tools
🪛 LanguageTool
[style] ~42-~42: Consider using “incompatible” to avoid wordiness.
Context: ...est versions of change-case (v5+
) are not compatible withWordPress
. InDokan utilities
,...(NOT_ABLE_PREMIUM)
🪛 Markdownlint (0.37.0)
15-15: null
Fenced code blocks should have a language specified(MD040, fenced-code-language)
docs/feature-override/readme.md (2)
104-108
: Fix code indentation in template dependencies array.The code uses tabs instead of spaces for indentation. Maintain consistent indentation throughout the codebase.
[ - 'slug' => 'products/products', - 'name' => 'listing', - ], + 'slug' => 'products/products', + 'name' => 'listing', + ],🧰 Tools
🪛 Markdownlint (0.37.0)
105-105: Column: 1
Hard tabs(MD010, no-hard-tabs)
106-106: Column: 1
Hard tabs(MD010, no-hard-tabs)
107-107: Column: 1
Hard tabs(MD010, no-hard-tabs)
156-162
: Add type hints and return type to filter callback.The filter callback should include parameter and return type hints for better type safety.
-add_filter( 'dokan_is_dashboard_nav_dependency_cleared', function ( $is_cleared, $route ) { +add_filter( 'dokan_is_dashboard_nav_dependency_cleared', function ( bool $is_cleared, string $route ): bool { if ( 'products' === $route ) { return true; }docs/frontend/dataviews.md (2)
28-28
: Fix grammar in component description.The sentence has a subject-verb agreement issue.
-Also, an example component are designed to interact with WordPress REST APIs. +Also, an example component is designed to interact with WordPress REST APIs.🧰 Tools
🪛 LanguageTool
[grammar] ~28-~28: “component” is a singular noun. It appears that the verb form is incorrect.
Context: ...r dashboard. Also, an example component are designed to interact with WordPress RES...(PCT_SINGULAR_NOUN_PLURAL_VERB_AGREEMENT)
208-225
: Enhance error handling in delete action.The delete action's error handling could be improved with more specific error messages and user feedback.
onClick={ async () => { try { const response = await fetch(`/wp-json/wp/v2/posts/${item.id}`, { method: 'DELETE', headers: { 'X-WP-Nonce': wpApiSettings.nonce, 'Content-Type': 'application/json' } }); - if (!response.ok) throw new Error('Failed to delete post'); + if (!response.ok) { + const error = await response.json(); + throw new Error(error.message || 'Failed to delete post'); + } fetchPosts(); closeModal(); } catch (error) { - console.error('Error deleting post:', error); + // Handle error appropriately + console.error('Error deleting post:', error.message); + // Show error message to user + wp.data.dispatch('core/notices').createErrorNotice( + error.message || 'Failed to delete post. Please try again.' + ); } } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.json
is excluded by!**/package-lock.json
📒 Files selected for processing (67)
base-tailwind.config.js
(1 hunks)docs/feature-override/readme.md
(1 hunks)docs/frontend/components.md
(1 hunks)docs/frontend/dataviews.md
(1 hunks)docs/frontend/utilities.md
(1 hunks)includes/Assets.php
(6 hunks)includes/DependencyManagement/Providers/CommonServiceProvider.php
(2 hunks)includes/REST/CustomersController.php
(1 hunks)includes/REST/DokanDataContinentsController.php
(1 hunks)includes/REST/DokanDataCountriesController.php
(1 hunks)includes/REST/Manager.php
(1 hunks)includes/REST/OrderControllerV3.php
(1 hunks)includes/REST/ProductController.php
(1 hunks)includes/REST/WithdrawController.php
(4 hunks)includes/REST/WithdrawControllerV2.php
(4 hunks)includes/VendorNavMenuChecker.php
(1 hunks)includes/Withdraw/Withdraws.php
(1 hunks)package.json
(3 hunks)src/Components/DataTable.tsx
(1 hunks)src/Components/DateTimeHtml.tsx
(1 hunks)src/Components/DokanTooltip.tsx
(1 hunks)src/Components/Pagination.tsx
(1 hunks)src/Components/PriceHtml.tsx
(1 hunks)src/Dashboard/Withdraw/Balance.tsx
(1 hunks)src/Dashboard/Withdraw/Hooks/useBalance.ts
(1 hunks)src/Dashboard/Withdraw/Hooks/useCharge.ts
(1 hunks)src/Dashboard/Withdraw/Hooks/useMakeDefaultMethod.ts
(1 hunks)src/Dashboard/Withdraw/Hooks/useWithdraw.ts
(1 hunks)src/Dashboard/Withdraw/Hooks/useWithdrawRequests.ts
(1 hunks)src/Dashboard/Withdraw/Hooks/useWithdrawSettings.ts
(1 hunks)src/Dashboard/Withdraw/PaymentDetails.tsx
(1 hunks)src/Dashboard/Withdraw/PaymentMethods.tsx
(1 hunks)src/Dashboard/Withdraw/RequestList.tsx
(1 hunks)src/Dashboard/Withdraw/RequestWithdrawBtn.tsx
(1 hunks)src/Dashboard/Withdraw/TableSkeleton.tsx
(1 hunks)src/Dashboard/Withdraw/WithdrawRequests.tsx
(1 hunks)src/Dashboard/Withdraw/index.tsx
(1 hunks)src/Dashboard/Withdraw/tailwind.scss
(1 hunks)src/Definitions/Continents.ts
(1 hunks)src/Definitions/CountryState.ts
(1 hunks)src/Definitions/Customers.ts
(1 hunks)src/Definitions/Order.ts
(1 hunks)src/Definitions/Product.ts
(1 hunks)src/Definitions/RouterProps.ts
(1 hunks)src/Definitions/window-types.ts
(1 hunks)src/Definitions/woocommerce-accounting.d.ts
(1 hunks)src/Routing/index.tsx
(1 hunks)src/base-tailwind.scss
(1 hunks)src/components/dataviews/DataViewTable.tsx
(1 hunks)src/components/dataviews/style.scss
(1 hunks)src/components/index.tsx
(1 hunks)src/dashboard/index.tsx
(1 hunks)src/dashboard/tailwind.scss
(1 hunks)src/hooks/ViewportDimensions.ts
(1 hunks)src/hooks/useCurrentUser.ts
(1 hunks)src/layout/404.tsx
(1 hunks)src/layout/ContentArea.tsx
(1 hunks)src/layout/Footer.tsx
(1 hunks)src/layout/Header.tsx
(1 hunks)src/layout/Sidebar.tsx
(1 hunks)src/layout/index.tsx
(1 hunks)src/utilities/ChangeCase.ts
(1 hunks)src/utilities/index.ts
(1 hunks)tests/php/src/REST/CustomersControllerTest.php
(1 hunks)tests/php/src/VendorNavMenuCheckerTest.php
(1 hunks)webpack-entries.js
(1 hunks)webpack.config.js
(1 hunks)
✅ Files skipped from review due to trivial changes (6)
- src/components/dataviews/style.scss
- src/layout/Footer.tsx
- webpack-entries.js
- src/layout/Sidebar.tsx
- src/utilities/index.ts
- src/utilities/ChangeCase.ts
👮 Files not reviewed due to content moderation or server errors (4)
- tests/php/src/VendorNavMenuCheckerTest.php
- tests/php/src/REST/CustomersControllerTest.php
- includes/REST/WithdrawController.php
- includes/REST/ProductController.php
🧰 Additional context used
🪛 Biome (1.9.4)
src/Definitions/window-types.ts
[error] 30-31: This empty export is useless because there's another export or import.
This import makes useless the empty export.
Safe fix: Remove this useless empty export.
(lint/complexity/noUselessEmptyExport)
src/Dashboard/Withdraw/PaymentDetails.tsx
[error] 46-46: Do not access Object.prototype method 'hasOwnProperty' from target object.
It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.
(lint/suspicious/noPrototypeBuiltins)
src/Dashboard/Withdraw/PaymentMethods.tsx
[error] 111-111: Do not access Object.prototype method 'hasOwnProperty' from target object.
It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.
(lint/suspicious/noPrototypeBuiltins)
src/Components/DataTable.tsx
[error] 36-36: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
src/hooks/useCurrentUser.ts
[error] 27-27: void is confusing inside a union type.
Unsafe fix: Use undefined instead.
(lint/suspicious/noConfusingVoidType)
[error] 38-38: void is confusing inside a union type.
Unsafe fix: Use undefined instead.
(lint/suspicious/noConfusingVoidType)
src/Dashboard/Withdraw/Balance.tsx
[error] 43-43: Do not access Object.prototype method 'hasOwnProperty' from target object.
It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.
(lint/suspicious/noPrototypeBuiltins)
webpack.config.js
[error] 2-2: Illegal use of reserved keyword package
as an identifier in strict mode
(parse)
src/Definitions/Order.ts
[error] 21-21: Expected a class, a function, or a variable declaration but instead found 'export'.
Expected a class, a function, or a variable declaration here.
(parse)
[error] 65-65: Expected a class, a function, or a variable declaration but instead found 'export'.
Expected a class, a function, or a variable declaration here.
(parse)
🪛 LanguageTool
docs/frontend/components.md
[uncategorized] ~55-~55: You might be missing the article “a” here.
Context: ...include the dokan-react-components
as scripts dependency and the @dokan/components
...
(AI_EN_LECTOR_MISSING_DETERMINER_A)
docs/frontend/dataviews.md
[grammar] ~28-~28: “component” is a singular noun. It appears that the verb form is incorrect.
Context: ...r dashboard. Also, an example component are designed to interact with WordPress RES...
(PCT_SINGULAR_NOUN_PLURAL_VERB_AGREEMENT)
[uncategorized] ~534-~534: The preposition ‘to’ seems more likely in this position.
Context: ... need to control paginationInfo
props for calculate `total pagination item & page...
(AI_HYDRA_LEO_REPLACE_FOR_TO)
[style] ~534-~534: You have already used this phrasing in nearby sentences. Consider replacing it to add variety to your writing.
Context: ...otal pagination item & pages. Also, we need to set
perPage&
pagein the
view` st...
(REP_NEED_TO_VB)
[uncategorized] ~534-~534: The preposition ‘to’ seems more likely in this position.
Context: ... perPage
& page
in the view
state for manage the pagination. #### ~ Set pagi...
(AI_HYDRA_LEO_REPLACE_FOR_TO)
[style] ~569-~569: You have already used this phrasing in nearby sentences. Consider replacing it to add variety to your writing.
Context: ...lected items in the DataViewTable
. We need to configure action definitions and handle...
(REP_NEED_TO_VB)
[style] ~571-~571: You have already used this phrasing in nearby sentences. Consider replacing it to add variety to your writing.
Context: ...nitions and handle bulk operations. We need to enable supportsBulk
props in table `a...
(REP_NEED_TO_VB)
[uncategorized] ~571-~571: The preposition ‘to’ seems more likely in this position.
Context: ...supportsBulk
props in table actions
for handle the bulk actions. Also, we need ...
(AI_HYDRA_LEO_REPLACE_FOR_TO)
[style] ~571-~571: You have already used this phrasing in nearby sentences. Consider replacing it to add variety to your writing.
Context: ...for handle the bulk actions. Also, we need to set
selection&
onChangeSelection` i...
(REP_NEED_TO_VB)
[uncategorized] ~571-~571: The preposition ‘to’ seems more likely in this position.
Context: ...onChangeSelection
in the view
state for manage the bulk selection. We can set `...
(AI_HYDRA_LEO_REPLACE_FOR_TO)
[misspelling] ~621-~621: Use “a” instead of ‘an’ if the following word doesn’t start with a vowel sound, e.g. ‘a sentence’, ‘a university’.
Context: ...to DataViews
: a function that returns an unique identifier for the record. ### ...
(EN_A_VS_AN)
[uncategorized] ~626-~626: Possible missing article found.
Context: ...t to modify a table from the outside of module or feature, we can use it. const a...
(AI_HYDRA_LEO_MISSING_A)
[typographical] ~650-~650: Consider adding a comma.
Context: ... want to use the default responsive view then don't need to pass the responsive
pro...
(IF_THEN_COMMA)
[uncategorized] ~669-~669: The preposition ‘to’ seems more likely in this position.
Context: ... There have another property filterBy
for handle the filter condition. **filterB...
(AI_HYDRA_LEO_REPLACE_FOR_TO)
[grammar] ~675-~675: It seems that a pronoun is missing.
Context: ...arameter and should return a ReactNode. If need to handle the field value before r...
(IF_VB)
[uncategorized] ~683-~683: Possible missing article found.
Context: ... in the UI, typically in the tooltip of action button. icon (string) : The icon...
(AI_HYDRA_LEO_MISSING_AN)
[style] ~705-~705: ‘in conjunction with’ might be wordy. Consider a shorter alternative.
Context: ...r) :** Current active page number. Used in conjunction with perPage
for pagination
. **search...
(EN_WORDINESS_PREMIUM_IN_CONJUNCTION_WITH)
[style] ~727-~727: To form a complete sentence, be sure to include a subject.
Context: ... (array) :** List of visible field IDs. Can be used to control which columns are di...
(MISSING_IT_THERE)
docs/feature-override/readme.md
[style] ~6-~6: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...#declare-react-menu-in-dokan-lite) - [Declare React
menu in Dokan Pro or **Exte...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~10-~10: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...in-dokan-pro-or-external-plugin) - [Define the override templates array structure....
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[uncategorized] ~18-~18: You might be missing the article “the” here.
Context: ...vailable in React
, you need to define route
property during the menu registra...
(AI_EN_LECTOR_MISSING_DETERMINER_THE)
[grammar] ~63-~63: “React” is a proper noun and needs to be capitalized.
Context: ...h menu which we are indicating that the react route is available. This will be used ...
(A_GOOGLE)
[grammar] ~64-~64: “React” is a proper noun and needs to be capitalized.
Context: ...etermine if the menu is pointing to the react Application or to the Legacy PHP Route....
(A_GOOGLE)
[uncategorized] ~92-~92: Use a comma before ‘and’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...ritten in PHP to the React
application and you want that if some of the PHP templa...
(COMMA_COMPOUND_SENTENCE)
[style] ~112-~112: In contexts where ‘if’ is followed by ‘or’, using ‘whether’ may be more appropriate (and formal).
Context: ...e route. This will be used to determine if the override templates are available fo...
(IF_WHETHER)
[uncategorized] ~149-~149: You might be missing the article “the” here.
Context: ...hich are passed to the template file in dokan_get_template_part()
function. (Op...
(AI_EN_LECTOR_MISSING_DETERMINER_THE)
[uncategorized] ~152-~152: Use a comma before ‘but’ if it connects two independent clauses (unless they are closely connected and short).
Context: ...erride any of the template file directly but you have override functionality by usin...
(COMMA_COMPOUND_SENTENCE)
docs/frontend/utilities.md
[style] ~42-~42: Consider using “incompatible” to avoid wordiness.
Context: ...est versions of change-case (v5+
) are not compatible with WordPress
. In Dokan utilities
,...
(NOT_ABLE_PREMIUM)
🪛 Markdownlint (0.37.0)
docs/frontend/components.md
68-68: null
Fenced code blocks should have a language specified
(MD040, fenced-code-language)
docs/frontend/dataviews.md
6-6: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
7-7: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
8-8: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
9-9: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
10-10: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
12-12: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
13-13: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
14-14: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
15-15: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
16-16: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
17-17: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
18-18: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
19-19: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
20-20: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
21-21: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
22-22: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
23-23: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
24-24: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
69-69: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
95-95: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
374-374: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
387-387: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
395-395: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
418-418: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
431-431: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
443-443: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
461-461: Punctuation: ':'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
480-480: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
505-505: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
514-514: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
536-536: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
556-556: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
590-590: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
604-604: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
628-628: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
652-652: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
696-696: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
711-711: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
723-723: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
732-732: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
739-739: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
753-753: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
759-759: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
765-765: Expected: fenced; Actual: indented
Code block style
(MD046, code-block-style)
5-5: null
Link fragments should be valid
(MD051, link-fragments)
11-11: null
Link fragments should be valid
(MD051, link-fragments)
18-18: null
Link fragments should be valid
(MD051, link-fragments)
19-19: null
Link fragments should be valid
(MD051, link-fragments)
21-21: null
Link fragments should be valid
(MD051, link-fragments)
22-22: null
Link fragments should be valid
(MD051, link-fragments)
23-23: null
Link fragments should be valid
(MD051, link-fragments)
docs/feature-override/readme.md
8-8: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
9-9: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
10-10: Expected: 2; Actual: 4
Unordered list indentation
(MD007, ul-indent)
105-105: Column: 1
Hard tabs
(MD010, no-hard-tabs)
106-106: Column: 1
Hard tabs
(MD010, no-hard-tabs)
107-107: Column: 1
Hard tabs
(MD010, no-hard-tabs)
1-1: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
17-17: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
20-20: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
72-72: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
90-90: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
93-93: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
114-114: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
130-130: Punctuation: '.'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
docs/frontend/utilities.md
15-15: null
Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🔇 Additional comments (28)
includes/REST/DokanDataCountriesController.php (2)
17-24
: Verify REST API Namespace and Route BaseThe namespace is set to
'dokan/v1'
, and the route base is'data/countries'
. Ensure these values are correctly aligned with the existing API structure and do not conflict with other endpoints.
85-98
:⚠️ Potential issuePotential Capability Check Issue
The capability
'dokandar'
may not be a standard WordPress capability. Ensure that it's correctly defined and that the users have the intended capabilities.Run the following script to check user capabilities:
This will help verify if
'dokandar'
is a valid capability assigned to vendors.includes/REST/DokanDataContinentsController.php (2)
17-24
: Verify REST API Namespace and Route BaseConfirm that the namespace
'dokan/v1'
and route base'data/continents'
are appropriate and do not conflict with existing endpoints.
85-98
:⚠️ Potential issuePotential Capability Check Issue
Verify if
'dokandar'
is a valid capability. It might need to be a role or specific capability string.Run the following script to verify capabilities:
✅ Verification successful
'dokandar' is a Valid Custom Capability
The 'dokandar' capability is properly registered, managed, and used consistently throughout the Dokan plugin. It's added to appropriate roles during installation and follows WordPress capability best practices.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: List capabilities for the 'vendor' role. wp role get vendor --fields=capabilitiesLength of output: 135
Script:
#!/bin/bash # Search for 'dokandar' usage in the codebase echo "=== Searching for 'dokandar' usage ===" rg "dokandar" -B 2 -A 2 echo -e "\n=== Searching for capability registration patterns ===" rg "add_cap|register_capability|capabilities" -B 2 -A 2 echo -e "\n=== Finding dokan_admin_menu_capability definition ===" ast-grep --pattern 'function dokan_admin_menu_capability'Length of output: 109052
Script:
#!/bin/bash # Search for dokan_admin_menu_capability definition and usage rg "function dokan_admin_menu_capability" -A 5 rg "dokan_admin_menu_capability\(\)" -B 2 -A 2Length of output: 1849
includes/VendorNavMenuChecker.php (4)
148-148
: Review Template Path FiltersEnsure that the
dokan_set_template_path
filter anddokan()->template_path()
are returning correct paths, and that this aligns with the intended template loading mechanism.
162-164
: Ensure Filter Provides Necessary ParametersVerify that the
dokan_get_template_part
filter passes all required parameters to function correctly and that any additional expected parameters are included.
139-164
: Optimize Template Retrieval LogicReview the logic in
get_overridden_template
to ensure it efficiently determines overridden templates and adheres to WordPress standards for template loading.
106-117
: 🛠️ Refactor suggestionCompatibility with PHP Versions
The use of arrow functions (
fn
) requires PHP 7.4 or higher. If supporting earlier versions, replace arrow functions with anonymous functions.Apply this diff:
- $resolved_dependencies = array_map( - fn( $dependency_array ): array => array_filter( - array_map( - fn( $dependency ) => $this->get_overridden_template( - $dependency['slug'], - $dependency['name'] ?? '', - $dependency['args'] ?? [] - ), - $dependency_array - ) - ), - $dependencies - ); + $resolved_dependencies = array_map( + function( $dependency_array ): array { + return array_filter( + array_map( + function( $dependency ) { + return $this->get_overridden_template( + $dependency['slug'], + isset( $dependency['name'] ) ? $dependency['name'] : '', + isset( $dependency['args'] ) ? $dependency['args'] : [] + ); + }, + $dependency_array + ) + ); + }, + $dependencies + );Verify the minimum PHP version requirement for the plugin.
includes/REST/CustomersController.php (1)
14-363
: Overall Code Quality and StructureThe
CustomersController
class is well-structured, extendingWC_REST_Customers_Controller
effectively. The use of theperform_vendor_action
method to wrap parent methods ensures consistent permission handling. The code is clean, well-documented, and follows best practices.includes/Assets.php (2)
366-377
: Verify Stylesheet Dependencies and Enqueue OrderThe stylesheets
dokan-react-frontend
anddokan-react-components
have dependencies on each other and onwp-components
. Ensure that these dependencies are correctly registered and that the stylesheets are enqueued in the proper order to prevent styling issues.
366-368
: Ensuredokan-tailwind
Style Is EnqueuedThe
dokan-tailwind
stylesheet is registered but not enqueued. If it's required for the Tailwind CSS styles to take effect, ensure that it is enqueued in the appropriate place.src/Components/PriceHtml.tsx (1)
44-53
: Consider security implications of using RawHTMLUsing RawHTML with formatted money values could potentially lead to XSS vulnerabilities if the accounting library output isn't properly sanitized.
src/Dashboard/Withdraw/Hooks/useMakeDefaultMethod.ts (2)
4-8
: Well-structured TypeScript interface!The interface clearly defines the hook's return type with proper TypeScript types for all properties.
20-24
: Consider adding response type validationThe API call lacks type validation for the response. Consider adding a type guard or schema validation to ensure the response matches expected format.
src/hooks/ViewportDimensions.ts (1)
28-33
: Good use of requestAnimationFrame!The implementation correctly uses requestAnimationFrame for performance optimization when handling resize events.
src/Components/DateTimeHtml.tsx (1)
12-14
: Add date string validationConsider adding validation for the date/time string format to prevent potential formatting errors.
Also applies to: 33-35, 53-55
src/Dashboard/Withdraw/Hooks/useWithdrawSettings.ts (1)
41-44
: Consider updating API version to v3The hook is using
/dokan/v2/withdraw/settings
while new endpoints are being introduced in v3. Consider updating to maintain version consistency across the application.src/Dashboard/Withdraw/Hooks/useBalance.ts (1)
50-53
: Consider updating API version to v3The hook is using
/dokan/v1/withdraw/balance
. Consider updating to v3 to maintain consistency with other endpoints.src/layout/index.tsx (1)
25-36
: LGTM! Well-structured type definitionThe
DokanRoute
type is well-defined with clear optional properties and proper JSX element types.includes/DependencyManagement/Providers/CommonServiceProvider.php (1)
69-71
: LGTM! Service registration follows established patternThe registration of
VendorNavMenuChecker
follows the same pattern as other services in the container.webpack.config.js (1)
11-19
: LGTM! Well-structured entry points configuration.The entry points configuration is well-organized, properly spreading existing entry points while adding new ones for components and utilities.
src/components/dataviews/DataViewTable.tsx (1)
82-82
:⚠️ Potential issueFix incorrect slot name for after-table slot
The slot name for the after-table slot incorrectly uses "before" instead of "after".
-<Slot name={ `dokan-before-vendor-data-table-${ tableNameSpace }` } fillProps={{ ...filteredProps }} /> +<Slot name={ `dokan-after-vendor-data-table-${ tableNameSpace }` } fillProps={{ ...filteredProps }} />Likely invalid or redundant comment.
includes/REST/WithdrawControllerV2.php (1)
49-65
: LGTM! Well-structured route registration.The route registration is well-implemented with proper argument validation and enum constraint for the method parameter.
src/Dashboard/Withdraw/PaymentMethods.tsx (2)
1-53
: Well-structured component setup with proper TypeScript typing!The component is well-organized with proper type definitions and necessary imports. The use of TypeScript for prop types enhances code reliability.
109-162
: Clean and efficient render logic implementation!The render logic demonstrates good practices:
- Proper loading state management
- Efficient use of conditional rendering
- Well-structured layout using Card components
🧰 Tools
🪛 Biome (1.9.4)
[error] 111-111: Do not access Object.prototype method 'hasOwnProperty' from target object.
It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.(lint/suspicious/noPrototypeBuiltins)
src/base-tailwind.scss (1)
6-21
: Well-structured table reset implementation.The table reset styles are properly scoped within the
.dokan-layout
class using@layer base
, following Tailwind CSS best practices. The comprehensive reset ensures consistent table styling across different browsers.src/Definitions/Customers.ts (1)
20-36
: Ensure consistency in email field requirements.The
CustomerAddress
but required inCustomer
. Consider documenting this design decision or making it consistent across interfaces.package.json (1)
27-27
: Verify compatibility between WordPress packages.The significant version jump in
@wordpress/scripts
(^30.7.0) and the addition of various WordPress packages might lead to compatibility issues. Please verify that all WordPress packages work together correctly.Also applies to: 58-65
✅ Verification successful
WordPress packages compatibility verified successfully
The package dependencies analysis shows compatible version ranges across all WordPress and related packages. The peer dependencies are well-aligned, with no conflicting version requirements detected.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for peer dependency warnings in package-lock.json jq -r '.packages | .[] | select(.peerDependencies != null) | .name + " requires: " + (.peerDependencies | to_entries | map(.key + "@" + .value) | join(", "))' package-lock.jsonLength of output: 12641
export type WeightUnit = Country['weight_unit']; | ||
|
||
|
||
export type Continents = Continent |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix incorrect type definition.
The Continents type should be an array of Continent objects, not a single Continent.
-export type Continents = Continent
+export type Continents = Continent[]
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
export type Continents = Continent | |
export type Continents = Continent[] |
export function isContinent(value: any): value is Continent { | ||
return ( | ||
typeof value === 'object' && | ||
value !== null && | ||
'code' in value && | ||
'name' in value && | ||
'countries' in value && | ||
'_links' in value && | ||
Array.isArray(value.countries) | ||
); | ||
} | ||
|
||
// Type guard to check if a value is a Country | ||
export function isCountry(value: any): value is Country { | ||
return ( | ||
typeof value === 'object' && | ||
value !== null && | ||
'code' in value && | ||
'name' in value && | ||
'currency_code' in value && | ||
'currency_pos' in value && | ||
'states' in value && | ||
Array.isArray(value.states) | ||
); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve type guard implementation.
The type guards could be more robust with additional validation and better typing.
-export function isContinent(value: any): value is Continent {
+export function isContinent(value: unknown): value is Continent {
return (
typeof value === 'object' &&
value !== null &&
'code' in value &&
+ typeof (value as Continent).code === 'string' &&
'name' in value &&
+ typeof (value as Continent).name === 'string' &&
'countries' in value &&
'_links' in value &&
- Array.isArray(value.countries)
+ Array.isArray((value as Continent).countries) &&
+ (value as Continent).countries.every(isCountry)
);
}
-export function isCountry(value: any): value is Country {
+export function isCountry(value: unknown): value is Country {
return (
typeof value === 'object' &&
value !== null &&
'code' in value &&
+ typeof (value as Country).code === 'string' &&
'name' in value &&
'currency_code' in value &&
'currency_pos' in value &&
'states' in value &&
- Array.isArray(value.states)
+ Array.isArray((value as Country).states) &&
+ (value as Country).states.every(isState)
);
}
+export function isState(value: unknown): value is State {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'code' in value &&
+ typeof (value as State).code === 'string' &&
+ 'name' in value &&
+ typeof (value as State).name === 'string'
+ );
+}
Committable suggestion skipped: line range outside the PR's diff.
public function add_subscriptions_read_permission_to_vendors( $permission, $context, $object_id, $obj ) { | ||
if ( 'read' === $context ) { | ||
return true; | ||
} | ||
|
||
return $permission; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Method Name Misalignment
The method add_subscriptions_read_permission_to_vendors
is misleading, as it modifies permissions for countries data, not subscriptions. Rename the method for clarity.
Apply this diff:
- public function add_subscriptions_read_permission_to_vendors( $permission, $context, $object_id, $obj ) {
+ public function modify_read_permission_for_vendors( $permission, $context, $object_id, $obj ) {
Also, update the filter hook:
- add_filter( 'woocommerce_rest_check_permissions', [ $this, 'add_subscriptions_read_permission_to_vendors' ], 10, 4 );
+ add_filter( 'woocommerce_rest_check_permissions', [ $this, 'modify_read_permission_for_vendors' ], 10, 4 );
Committable suggestion skipped: line range outside the PR's diff.
public function add_subscriptions_read_permission_to_vendors( $permission, $context, $object_id, $obj ) { | ||
if ( 'read' === $context ) { | ||
return true; | ||
} | ||
|
||
return $permission; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Method Name Misalignment
The method add_subscriptions_read_permission_to_vendors
suggests it's for subscriptions, but it's used for continents data. Rename for clarity.
Apply this diff:
- public function add_subscriptions_read_permission_to_vendors( $permission, $context, $object_id, $obj ) {
+ public function modify_read_permission_for_vendors( $permission, $context, $object_id, $obj ) {
Update the filter hook accordingly:
- add_filter( 'woocommerce_rest_check_permissions', [ $this, 'add_subscriptions_read_permission_to_vendors' ], 10, 4 );
+ add_filter( 'woocommerce_rest_check_permissions', [ $this, 'modify_read_permission_for_vendors' ], 10, 4 );
Committable suggestion skipped: line range outside the PR's diff.
if ( ! current_user_can( 'edit_shop_orders' ) ) { | ||
return new WP_Error( 'dokan_rest_cannot_search', __( 'You do not have permission to search customers.', 'dokan-lite' ), [ 'status' => rest_authorization_required_code() ] ); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Inconsistent Permission Check in search_customers
Method
The search_customers
method uses current_user_can( 'edit_shop_orders' )
for permission checking, which is inconsistent with other methods that use the check_permission
method. For consistency and to centralize permission logic, consider refactoring search_customers
to use check_permission
.
Apply this diff to align permission checks:
public function search_customers( $request ) {
- if ( ! current_user_can( 'edit_shop_orders' ) ) {
- return new WP_Error( 'dokan_rest_cannot_search', __( 'You do not have permission to search customers.', 'dokan-lite' ), [ 'status' => rest_authorization_required_code() ] );
- }
+ $permission_check = $this->check_permission( $request, 'search' );
+ if ( is_wp_error( $permission_check ) ) {
+ return $permission_check;
+ }
Committable suggestion skipped: line range outside the PR's diff.
if ( | ||
! bodyData || | ||
! bodyData.hasOwnProperty( 'isLoading' ) || | ||
bodyData.isLoading || | ||
masterLoading | ||
) { | ||
return <Loader />; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Replace hasOwnProperty with Object.hasOwn.
Using Object.prototype.hasOwnProperty directly on objects can be unsafe. Use Object.hasOwn instead.
- if (
- !bodyData ||
- !bodyData.hasOwnProperty('isLoading') ||
- bodyData.isLoading ||
- masterLoading
- ) {
+ if (
+ !bodyData ||
+ !Object.hasOwn(bodyData, 'isLoading') ||
+ bodyData.isLoading ||
+ masterLoading
+ ) {
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if ( | |
! bodyData || | |
! bodyData.hasOwnProperty( 'isLoading' ) || | |
bodyData.isLoading || | |
masterLoading | |
) { | |
return <Loader />; | |
} | |
if ( | |
!bodyData || | |
!Object.hasOwn(bodyData, 'isLoading') || | |
bodyData.isLoading || | |
masterLoading | |
) { | |
return <Loader />; | |
} |
🧰 Tools
🪛 Biome (1.9.4)
[error] 46-46: Do not access Object.prototype method 'hasOwnProperty' from target object.
It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.
(lint/suspicious/noPrototypeBuiltins)
<MaskedInput | ||
label={ __( 'Withdraw amount', 'dokan' ) } | ||
className="focus:border-none" | ||
addOnLeft={ currencySymbol } | ||
defaultValue={ withdrawAmount } | ||
onChange={ ( e ) => { | ||
debouncedWithdrawAmount( | ||
e.target.value | ||
); | ||
} } | ||
maskRule={ { | ||
numeral: true, | ||
numeralDecimalMark: | ||
window?.dokanCurrency?.decimal ?? | ||
'.', | ||
delimiter: | ||
window?.dokanCurrency?.thousand ?? | ||
',', | ||
numeralDecimalScale: | ||
window?.dokanCurrency?.precision ?? | ||
2, | ||
} } | ||
input={ { | ||
id: 'withdraw-amount', | ||
name: 'withdraw-amount', | ||
type: 'text', | ||
placeholder: __( | ||
'Enter amount', | ||
'dokan' | ||
), | ||
required: true, | ||
disabled: false, | ||
} } | ||
/> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add input validation for withdrawal amount.
The withdrawal amount input should include validation against minimum and maximum limits.
<MaskedInput
label={__('Withdraw amount', 'dokan')}
className="focus:border-none"
addOnLeft={currencySymbol}
defaultValue={withdrawAmount}
+ error={
+ withdrawAmount && (
+ Number(unformatNumber(withdrawAmount)) < settings?.data?.minimum_withdraw_amount
+ ? __('Amount is below minimum withdrawal limit', 'dokan')
+ : Number(unformatNumber(withdrawAmount)) > settings?.data?.maximum_withdraw_amount
+ ? __('Amount exceeds maximum withdrawal limit', 'dokan')
+ : undefined
+ )
+ }
onChange={(e) => {
debouncedWithdrawAmount(e.target.value);
}}
Committable suggestion skipped: line range outside the PR's diff.
[role-dialog] { | ||
z-index: 9999; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix HTML attribute selector syntax and consider z-index value.
- The attribute selector
[role-dialog]
is incorrect. HTML attributes with values should use quotes:[role="dialog"]
. - The z-index value of 9999 is extremely high. Consider using a lower value or implementing a z-index management system.
- [role-dialog] {
+ [role="dialog"] {
- z-index: 9999;
+ z-index: 100;
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
[role-dialog] { | |
z-index: 9999; | |
} | |
[role="dialog"] { | |
z-index: 100; | |
} |
table, th, td { | ||
margin: 0; | ||
padding: 0; | ||
border: 0; | ||
border-spacing: 0; | ||
border-collapse: collapse; | ||
font-size: inherit; | ||
font-weight: inherit; | ||
text-align: inherit; | ||
vertical-align: inherit; | ||
box-sizing: border-box; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove duplicate table reset styles.
These table reset styles are duplicated from src/base-tailwind.scss
. Consider importing and reusing the existing styles instead of duplicating them.
|
||
### Output: | ||
|
||
<a href="https://ibb.co.com/YfyLf6N"><img src="https://i.ibb.co.com/Dw8RwN1/Screenshot-2024-12-26-at-11-25-33-AM.png" alt="Screenshot-2024-12-26-at-11-25-33-AM" border="0"></a> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Fix incorrect ImageBB domain in URLs
The image links are broken due to incorrect domain usage. Remove .com
from both URLs:
- Change
https://ibb.co.com/YfyLf6N
tohttps://ibb.co/YfyLf6N
- Change
https://i.ibb.co.com/Dw8RwN1/...
tohttps://i.ibb.co/Dw8RwN1/...
🔗 Analysis chain
Fix broken image link.
The image link appears to be broken or inaccessible. Consider using a more reliable image hosting service or including the image in the repository.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Verify if the image exists in the repository
fd -t f "Screenshot-2024-12-26-at-11-25-33-AM.png" docs/
Length of output: 56
Script:
#!/bin/bash
# Search for other image links in markdown files
rg -U "https://[^)]*ibb\.co[^)]*" docs/
Length of output: 1173
Script:
#!/bin/bash
# Double check for any other instances of the incorrect domain
rg -l "ibb\.co\.com" .
Length of output: 53
All Submissions:
Changes proposed in this Pull Request:
Related Pull Request(s)
Closes
How to test the changes in this Pull Request:
Changelog entry
Title
Detailed Description of the pull request. What was previous behaviour
and what will be changed in this PR.
Before Changes
Describe the issue before changes with screenshots(s).
After Changes
Describe the issue after changes with screenshot(s).
Feature Video (optional)
Link of detailed video if this PR is for a feature.
PR Self Review Checklist:
FOR PR REVIEWER ONLY:
Summary by CodeRabbit
Dokan Plugin Release Notes
New Features
Improvements
Bug Fixes
Performance
Documentation
Dependencies
Testing