diff --git a/backend/__tests__/inventory_controller.test.js b/backend/__tests__/inventory_controller.test.js new file mode 100644 index 0000000..4854338 --- /dev/null +++ b/backend/__tests__/inventory_controller.test.js @@ -0,0 +1,162 @@ +jest.mock('../lib/dynamodbClient', () => ({ + scan: jest.fn(), + put: jest.fn(), + update: jest.fn() +})); +jest.mock('axios', () => ({ get: jest.fn() })); + +const docClient = require('../lib/dynamodbClient'); +const axios = require('axios'); +const controller = require('../controllers/inventory_controller'); +const { createRes } = require('./testUtils'); + +describe('inventory controller', () => { + const timestamp = '2026-01-01T00:00:00.000Z'; + let res; + + beforeEach(() => { + jest.useFakeTimers().setSystemTime(new Date(timestamp)); + jest.replaceProperty(process, 'env', { + ...process.env, + EXTERNAL_INVENTORY_URL: 'https://inventory.example.test/items' + }); + for (const method of Object.values(docClient)) { + method.mockReset().mockReturnValue({ promise: async () => ({}) }); + } + axios.get.mockReset(); + res = createRes(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + jest.useRealTimers(); + }); + + test.each([ + [{ Items: [{ id: 'tomatoes' }] }, [{ id: 'tomatoes' }]], + [{}, []] + ])('lists inventory from scan result %j', async (result, expected) => { + docClient.scan.mockReturnValue({ promise: async () => result }); + + await controller.getInventory({}, res); + + expect(docClient.scan).toHaveBeenCalledWith({ TableName: 'Inventory' }); + expect(res.body).toEqual(expected); + expect(res.statusCode).toBe(200); + }); + + test('creates and returns inventory with model defaults', async () => { + const body = { id: 'tomatoes', name: 'Tomatoes', category: 'fresh', unit: 'kg' }; + + await controller.createInventory({ body }, res); + + expect(res.statusCode).toBe(201); + expect(res.body).toEqual({ + ...body, stock: 0, seasons: [], price: 0, batch: null, lot: null, + externalId: null, createdAt: timestamp, updatedAt: timestamp + }); + expect(docClient.put).toHaveBeenCalledWith({ TableName: 'Inventory', Item: res.body }); + }); + + test.each([ + [{}, '', {}], + [{ batch: 'harvest-1' }, ', batch = :b', { ':b': 'harvest-1' }], + [{ lot: 'field-2' }, ', lot = :l', { ':l': 'field-2' }], + [{ batch: '', lot: null }, ', batch = :b, lot = :l', { ':b': '', ':l': null }] + ])('updates stock with optional fields %j', async (fields, suffix, values) => { + const updated = { id: 'tomatoes', stock: 0, ...fields }; + docClient.update.mockReturnValue({ promise: async () => ({ Attributes: updated }) }); + + await controller.updateStock({ params: { id: updated.id }, body: { stock: 0, ...fields } }, res); + + expect(docClient.update).toHaveBeenCalledWith({ + TableName: 'Inventory', Key: { id: updated.id }, + UpdateExpression: `set stock = :s, updatedAt = :u${suffix}`, + ExpressionAttributeValues: { ':s': 0, ':u': timestamp, ...values }, + ReturnValues: 'ALL_NEW' + }); + expect(res.body).toEqual(updated); + }); + + test('updates price and returns stored attributes', async () => { + const updated = { id: 'tomatoes', price: 0 }; + docClient.update.mockReturnValue({ promise: async () => ({ Attributes: updated }) }); + + await controller.updatePrice({ params: { id: updated.id }, body: { price: 0 } }, res); + + expect(docClient.update).toHaveBeenCalledWith({ + TableName: 'Inventory', Key: { id: updated.id }, + UpdateExpression: 'set price = :p, updatedAt = :u', + ExpressionAttributeValues: { ':p': 0, ':u': timestamp }, + ReturnValues: 'ALL_NEW' + }); + expect(res.body).toEqual(updated); + }); + + test('imports external inventory through model normalization', async () => { + const items = ['tomatoes', 'beans'].map(id => ({ + id, name: id, category: 'fresh', stock: 12, unit: 'kg', seasons: ['summer'], + price: 3, batch: 'harvest-1', lot: 'field-2', externalId: `external-${id}`, + createdAt: '2025-12-01T00:00:00.000Z', updatedAt: timestamp + })); + axios.get.mockResolvedValue({ data: [...items, { id: 'kale', name: 'Kale', note: 'x' }] }); + + await controller.syncExternal({}, res); + + expect(axios.get.mock.calls[0][0]).toBe(process.env.EXTERNAL_INVENTORY_URL); + const normalized = { + id: 'kale', name: 'Kale', category: undefined, stock: 0, unit: undefined, + seasons: [], price: 0, batch: null, lot: null, externalId: null, + createdAt: timestamp, updatedAt: timestamp + }; + expect(docClient.put.mock.calls).toEqual([...items, normalized].map(Item => [{ TableName: 'Inventory', Item }])); + expect(res.body).toEqual({ imported: 3 }); + }); + + test.each([[], { items: [] }, null])('imports no records from %j', async data => { + axios.get.mockResolvedValue({ data }); + + await controller.syncExternal({}, res); + + expect(res.body).toEqual({ imported: 0 }); + expect(docClient.put).not.toHaveBeenCalled(); + }); + + test('rejects external sync when endpoint is not configured', async () => { + delete process.env.EXTERNAL_INVENTORY_URL; + + await controller.syncExternal({}, res); + + expect(res.statusCode).toBe(500); + expect(res.body).toEqual({ error: 'EXTERNAL_INVENTORY_URL not configured' }); + expect(axios.get).not.toHaveBeenCalled(); + expect(docClient.put).not.toHaveBeenCalled(); + }); + + test.each([ + ['getInventory', 'scan', 'Error fetching inventory'], + ['createInventory', 'put', 'Error creating inventory item'], + ['updateStock', 'update', 'Error updating stock'], + ['updatePrice', 'update', 'Error updating price'], + ['syncExternal', 'put', 'Error syncing external inventory'] + ])('%s reports storage failure', async (handler, method, error) => { + docClient[method].mockReturnValue({ promise: async () => { throw new Error('storage unavailable'); } }); + axios.get.mockResolvedValue({ data: [{ id: 'tomatoes' }, { id: 'beans' }] }); + + await controller[handler]({ params: { id: 'tomatoes' }, body: { stock: 1, price: 2 } }, res); + + expect(res.statusCode).toBe(500); + expect(res.body).toEqual({ error }); + expect(docClient[method]).toHaveBeenCalledTimes(1); + }); + + test('reports external fetch failure without writing inventory', async () => { + axios.get.mockRejectedValue(new Error('upstream unavailable')); + + await controller.syncExternal({}, res); + + expect(res.statusCode).toBe(500); + expect(res.body).toEqual({ error: 'Error syncing external inventory' }); + expect(docClient.put).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/__tests__/translation.test.js b/backend/__tests__/translation.test.js new file mode 100644 index 0000000..d1ed26b --- /dev/null +++ b/backend/__tests__/translation.test.js @@ -0,0 +1,74 @@ +const { translateMessage, translateTerm, qaCheck } = require('../utils/translation'); + +describe('translation', () => { + let warn; + + beforeEach(() => { + warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => jest.restoreAllMocks()); + + test.each([ + [undefined, 'listing'], + ['es', 'publicación'], + ['ES-MX', 'anuncio'], + ['es-AR', 'publicación'], + ['fr', 'annonce'], + ['fr-CA', 'annonce'], + ['unknown', 'listing'] + ])('resolves listing term for locale %s', (locale, expected) => { + expect(translateTerm('listing', locale)).toBe(expected); + }); + + test('inherits base terms and messages when dialect does not override them', () => { + expect(translateTerm('producerPlural', 'es-MX')).toBe('productores'); + expect(translateMessage('this_region', 'es-MX')).toBe('esta región'); + }); + + test.each(['en', 'es-MX', 'fr'])('preserves PING terminology for %s', locale => { + expect(translateTerm('ping', locale)).toBe('PING'); + expect(translateTerm('pingPlural', locale)).toBe('PINGs'); + }); + + test('returns unknown keys unchanged', () => { + expect(translateTerm('unknown_term', 'fr')).toBe('unknown_term'); + expect(translateMessage('unknown_message', 'es-MX')).toBe('unknown_message'); + expect(warn).not.toHaveBeenCalled(); + }); + + test('renders a message with supplied region and listing terms', () => { + expect(translateMessage('high_listing_volume', 'en', { + region: 'Oaxaca', listingTerm: 'listing', listingTermPlural: 'listings' + })).toBe('📈 High listing volume detected in Oaxaca – over 100 active listings.'); + expect(warn).not.toHaveBeenCalled(); + }); + + test('substitutes every occurrence of a placeholder', () => { + expect(translateMessage('{a} and {a}', 'en', { a: 'x' })).toBe('x and x'); + expect(warn).not.toHaveBeenCalled(); + }); + + test('renders dialect message with supplied variables', () => { + expect(translateMessage('low_market_activity', 'ES-MX', { region: 'Oaxaca' })) + .toBe('🌱 Poca movida de mercado en Oaxaca. Difunde qué se anda buscando.'); + expect(warn).not.toHaveBeenCalled(); + }); + + test('uses English messages for unknown locale', () => { + expect(translateMessage('this_region', 'unknown')).toBe('this region'); + expect(translateMessage('this_region')).toBe('this region'); + }); + + test('reports unresolved placeholders without changing output', () => { + const output = translateMessage('top_rated_producers', 'en', { names: 'Ada' }); + + expect(output).toBe('🏆 Top rated {producerTermPlural} this week: Ada'); + expect(warn).toHaveBeenCalledWith('Unresolved placeholder in translation:', output); + }); + + test('accepts complete text without warnings', () => { + expect(qaCheck('Market update')).toBe('Market update'); + expect(warn).not.toHaveBeenCalled(); + }); +});