Skip to content

Commit

Permalink
add payments (#7)
Browse files Browse the repository at this point in the history
* add payments

* remove unused import
  • Loading branch information
BramKaashoek authored Apr 21, 2021
1 parent 575ae56 commit ffa0996
Show file tree
Hide file tree
Showing 7 changed files with 206 additions and 3 deletions.
4 changes: 3 additions & 1 deletion src/ctMock.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { PaymentService } from './services/payment'
import nock from 'nock'
import express, { NextFunction, Request, Response } from 'express'
import supertest from 'supertest'
Expand Down Expand Up @@ -123,6 +124,7 @@ export class CommercetoolsMock {
this._storage
),
order: new OrderService(projectRouter, this._storage),
payment: new PaymentService(projectRouter, this._storage),
store: new StoreService(projectRouter, this._storage),
type: new TypeService(projectRouter, this._storage),
}
Expand All @@ -136,7 +138,7 @@ export class CommercetoolsMock {
})
} else {
return resp.status(500).send({
error: 'Unhandled error',
error: err.message,
})
}
})
Expand Down
23 changes: 23 additions & 0 deletions src/repositories/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
Money,
Price,
PriceDraft,
Reference,
ResourceIdentifier,
Store,
StoreKeyReference,
StoreResourceIdentifier,
Expand All @@ -27,6 +29,7 @@ export const createCustomFields = (
projectKey,
draft.type
) as Type

if (!typeResource) {
throw new Error(
`No type '${draft.type.typeId}' with id=${draft.type.id} or key=${draft.type.key}`
Expand Down Expand Up @@ -74,3 +77,23 @@ export const resolveStoreReference = (
key: store.key,
}
}

export const getReferenceFromResourceIdentifier = <T extends Reference>(
resourceIdentifier: ResourceIdentifier,
projectKey: string,
storage: AbstractStorage
): T => {
const resource = storage.getByResourceIdentifier(
projectKey,
resourceIdentifier
)
if (!resource)
throw new Error(
`resource type ${resourceIdentifier.typeId} with id ${resourceIdentifier.id} and key ${resourceIdentifier.key} not found`
)

return ({
typeId: resourceIdentifier.typeId,
id: resource?.id,
} as unknown) as T
}
81 changes: 81 additions & 0 deletions src/repositories/payment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import {
Payment,
PaymentDraft,
ReferenceTypeId,
StateReference,
Transaction,
} from '@commercetools/platform-sdk'
import AbstractRepository from './abstract'
import {
createCustomFields,
createTypedMoney,
getReferenceFromResourceIdentifier,
} from './helpers'
import { getBaseResourceProperties } from '../helpers'
import { v4 as uuidv4 } from 'uuid'

export class PaymentRepository extends AbstractRepository {
getTypeId(): ReferenceTypeId {
return 'payment'
}

create(projectKey: string, draft: PaymentDraft): Payment {
const resource: Payment = {
...getBaseResourceProperties(),
amountPlanned: createTypedMoney(draft.amountPlanned),
paymentMethodInfo: draft.paymentMethodInfo!,
paymentStatus: draft.paymentStatus
? {
...draft.paymentStatus,
state: draft.paymentStatus.state
? getReferenceFromResourceIdentifier<StateReference>(
draft.paymentStatus.state,
projectKey,
this._storage
)
: undefined,
}
: {},
transactions: (draft.transactions || []).map(
(t): Transaction => ({
...t,
id: uuidv4(),
amount: createTypedMoney(t.amount),
})
),
interfaceInteractions: (draft.interfaceInteractions || []).map(
interaction =>
createCustomFields(interaction, projectKey, this._storage)!
),
custom: createCustomFields(draft.custom, projectKey, this._storage),
}

this.save(projectKey, resource)
return resource
}

actions = {
// addInterfaceInteraction: () => {},
// addTransaction: () => {},
// changeAmountPlanned: () => {},
// changeTransactionInteractionId: () => {},
// changeTransactionState: () => {},
// changeTransactionTimestamp: () => {},
// setAmountPaid: () => {},
// setAmountRefunded: () => {},
// setAnonymousId: () => {},
// setAuthorization: () => {},
// setCustomField: () => {},
// setCustomType: () => {},
// setCustomer: () => {},
// setExternalId: () => {},
// setInterfaceId: () => {},
// setKey: () => {},
// setMethodInfoInterface: () => {},
// setMethodInfoMethod: () => {},
// setMethodInfoName: () => {},
// setStatusInterfaceCode: () => {},
// setStatusInterfaceText: () => {},
// transitionState: () => {},
}
}
77 changes: 77 additions & 0 deletions src/services/payment.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { PaymentDraft } from '@commercetools/platform-sdk'
import supertest from 'supertest'
import { CommercetoolsMock } from '../index'

const ctMock = new CommercetoolsMock()

describe('Payment', () => {
beforeEach(async () => {
const response = await supertest(ctMock.app)
.post('/dummy/types')
.send({
key: 'custom-payment',
name: {
'nl-NL': 'custom-payment',
},
resourceTypeIds: ['payment'],
})
expect(response.status).toBe(200)
})

test('Create payment', async () => {
const draft: PaymentDraft = {
amountPlanned: { currencyCode: 'EUR', centAmount: 1337 },
custom: {
type: { typeId: 'type', key: 'custom-payment' },
fields: {
foo: 'bar',
},
},
}
const response = await supertest(ctMock.app)
.post('/dummy/payments')
.send(draft)

expect(response.status).toBe(200)
expect(response.body).toEqual({
id: expect.anything(),
createdAt: expect.anything(),
lastModifiedAt: expect.anything(),
version: 1,
amountPlanned: {
type: 'centPrecision',
fractionDigits: 2,
currencyCode: 'EUR',
centAmount: 1337,
},
paymentStatus: {},
transactions: [],
interfaceInteractions: [],
custom: {
type: { typeId: 'type', id: expect.anything() },
fields: { foo: 'bar' },
},
})
})
test('Get payment', async () => {
const draft: PaymentDraft = {
amountPlanned: { currencyCode: 'EUR', centAmount: 1337 },
custom: {
type: { typeId: 'type', key: 'custom-payment' },
fields: {
foo: 'bar',
},
},
}
const createResponse = await supertest(ctMock.app)
.post('/dummy/payments')
.send(draft)

const response = await supertest(ctMock.app).get(
`/dummy/payments/${createResponse.body.id}`
)

expect(response.status).toBe(200)
expect(response.body).toEqual(createResponse.body)
})
})
17 changes: 17 additions & 0 deletions src/services/payment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import AbstractService from './abstract'
import { Router } from 'express'
import { AbstractStorage } from '../storage'
import { PaymentRepository } from 'repositories/payment'

export class PaymentService extends AbstractService {
public repository: PaymentRepository

constructor(parent: Router, storage: AbstractStorage) {
super(parent)
this.repository = new PaymentRepository(storage)
}

getBasePath() {
return 'payments'
}
}
2 changes: 2 additions & 0 deletions src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
ResourceIdentifier,
Store,
Type,
Payment,
} from '@commercetools/platform-sdk'
import { parseExpandClause } from './lib/expandParser'
import { ResourceMap, Writable } from 'types'
Expand Down Expand Up @@ -91,6 +92,7 @@ export class InMemoryStorage extends AbstractStorage {
'inventory-entry': new Map<string, InventoryEntry>(),
'key-value-document': new Map<string, CustomObject>(),
order: new Map<string, Order>(),
payment: new Map<string, Payment>(),
store: new Map<string, Store>(),
type: new Map<string, Type>(),
}
Expand Down
5 changes: 3 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { PaymentRepository } from 'repositories/payment'
import * as ctp from '@commercetools/platform-sdk'
import { ReferenceTypeId } from '@commercetools/platform-sdk'
import { CartRepository } from 'repositories/cart'
Expand Down Expand Up @@ -51,7 +52,7 @@ export type ResourceIdentifierMap = {
// 'cart': ctp.CartResourceIdentifier,
// 'category': ctp.CategoryResourceIdentifier,
channel: ctp.ChannelResourceIdentifier
// 'foobar': ctp.CustomerGroupResourceIdentifier,
payment: ctp.PaymentResourceIdentifier
// 'foobar': ctp.CustomerResourceIdentifier,
// 'foobar': ctp.DiscountCodeResourceIdentifier,
// 'foobar': ctp.InventoryEntryResourceIdentifier,
Expand Down Expand Up @@ -87,7 +88,7 @@ export type RepositoryMap = {
'inventory-entry': InventoryEntryRepository
order: OrderRepository
'order-edit': never
payment: never
payment: PaymentRepository
product: never
'product-discount': never
'product-type': never
Expand Down

0 comments on commit ffa0996

Please sign in to comment.