File size: 1,914 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
 */

import { recordTracksEvent } from '@automattic/calypso-analytics';
import { translate } from 'i18n-calypso';
import { closeAccountSuccess } from 'calypso/state/account/actions';
import { ACCOUNT_CLOSE } from 'calypso/state/action-types';
import { registerHandlers } from 'calypso/state/data-layer/handler-registry';
import { http } from 'calypso/state/data-layer/wpcom-http/actions';
import { dispatchRequest } from 'calypso/state/data-layer/wpcom-http/utils';
import { errorNotice } from 'calypso/state/notices/actions';

export function requestAccountClose( action ) {
	return http(
		{
			method: 'POST',
			apiVersion: '1.1',
			path: `/me/account/close`,
			body: {}, // have to have an empty body to make wpcom-http happy
		},
		action
	);
}

export function fromApi( response ) {
	// don't need to check for existence of response because errors are handled
	if ( ! response.success ) {
		throw new Error( 'Account closure was unsuccessful', response );
	}
	return response;
}

export function receiveAccountCloseSuccess( _action, response ) {
	recordTracksEvent( 'calypso_account_closed' );
	return closeAccountSuccess( response );
}

export function receiveAccountCloseError( _action, error ) {
	if ( error.error === 'active-subscriptions' ) {
		return errorNotice(
			translate( 'This user account cannot be closed while it has active subscriptions.' )
		);
	}

	if ( error.error === 'active-memberships' ) {
		return errorNotice(
			translate( 'This user account cannot be closed while it has active purchases.' )
		);
	}

	return errorNotice(
		translate( 'Sorry, there was a problem closing your account. Please contact support.' )
	);
}

registerHandlers( 'state/data-layer/wpcom/me/account/close/index.js', {
	[ ACCOUNT_CLOSE ]: [
		dispatchRequest( {
			fetch: requestAccountClose,
			onSuccess: receiveAccountCloseSuccess,
			onError: receiveAccountCloseError,
			fromApi,
		} ),
	],
} );