Skip to content
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

Permite a criação de conteúdos do tipo ad #1742

Merged
merged 4 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions models/authorization.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ function filterInput(user, feature, input, target) {
title: input.title,
body: input.body,
status: input.status,
type: input.type,
source_url: input.source_url,
};
}
Expand Down
5 changes: 4 additions & 1 deletion models/balance.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,17 @@ async function findAllByOriginatorId(originatorId, options) {
async function create({ balanceType, recipientId, amount, originatorType, originatorId }, options = {}) {
const tableName = tableNameMap[balanceType] || tableNameMap.default;
const hasBalanceTypeColum = balanceType.startsWith('content:tabcoin');
const totalBalanceFunction = sqlFunctionMap[balanceType] || sqlFunctionMap.default;

const returning = options.withBalance ? `*, ${totalBalanceFunction}($1) as total` : '*';

const query = {
text: `
INSERT INTO ${tableName}
(recipient_id, amount, originator_type, originator_id${hasBalanceTypeColum ? ', balance_type' : ''})
VALUES
($1, $2, $3, $4${hasBalanceTypeColum ? ', $5' : ''})
RETURNING * ;
RETURNING ${returning};
`,
values: [recipientId, amount, originatorType, originatorId],
};
Expand Down
51 changes: 48 additions & 3 deletions models/content.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { randomUUID as uuidV4 } from 'node:crypto';
import slug from 'slug';

import { ForbiddenError, ValidationError } from 'errors';
import { ForbiddenError, UnprocessableEntityError, ValidationError } from 'errors';
import database from 'infra/database.js';
import balance from 'models/balance.js';
import pagination from 'models/pagination.js';
Expand Down Expand Up @@ -113,6 +113,7 @@ async function findAll(values = {}, options = {}) {
contents.title,
${!values.attributes?.exclude?.includes('body') ? 'contents.body,' : ''}
contents.status,
contents.type,
contents.source_url,
contents.created_at,
contents.updated_at,
Expand Down Expand Up @@ -286,6 +287,11 @@ async function create(postedContent, options = {}) {
transaction: options.transaction,
});

await updateTabCashBalance(null, newContent, {
eventId: options.eventId,
transaction: options.transaction,
});

const tabcoinsCount = await balance.getContentTabcoinsCreditDebit(
{
recipientId: newContent.id,
Expand Down Expand Up @@ -317,8 +323,8 @@ async function create(postedContent, options = {}) {
),
inserted_content as (
INSERT INTO
contents (id, parent_id, owner_id, slug, title, body, status, source_url, published_at, path)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, parent.child_path
contents (id, parent_id, owner_id, slug, title, body, status, source_url, published_at, type, path)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, parent.child_path
FROM parent
RETURNING *
)
Expand All @@ -330,6 +336,7 @@ async function create(postedContent, options = {}) {
inserted_content.title,
inserted_content.body,
inserted_content.status,
inserted_content.type,
inserted_content.source_url,
inserted_content.created_at,
inserted_content.updated_at,
Expand All @@ -355,6 +362,7 @@ async function create(postedContent, options = {}) {
content.status,
content.source_url,
content.published_at,
content.type,
],
};

Expand Down Expand Up @@ -440,6 +448,7 @@ function validateCreateSchema(content) {
title: 'optional',
body: 'required',
status: 'required',
content_type: 'optional',
source_url: 'optional',
});

Expand Down Expand Up @@ -550,6 +559,11 @@ async function creditOrDebitTabCoins(oldContent, newContent, options = {}) {
});
}

// We should not credit TabCoins to the user if the "type" is not "content".
if (newContent.type !== 'content') {
userEarnings = 0;
}

// We should not credit if the content has little or no value.
if (newContent.body.split(/[a-z]{5,}/i, 6).length < 6) return;

Expand Down Expand Up @@ -602,6 +616,36 @@ async function creditOrDebitTabCoins(oldContent, newContent, options = {}) {
}
}

async function updateTabCashBalance(oldContent, newContent, options = {}) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esqueceu de remover o oldContent?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Foi over engineering mesmo 😅

Tem diversos casos que precisamos lidar, mas que eu não implementei porque preciso entender melhor a ideia do Filipe. Só que é praticamente certo que iremos chamar essa função no PATCH, então já deixei padronizada com a mesma interface de creditOrDebitTabCoins.

Bora pro merge!

if (newContent.type === 'content') {
return;
}

const tabCashToDebitFromUser = -100;

const balanceResult = await balance.create(
{
balanceType: 'user:tabcash',
recipientId: newContent.owner_id,
amount: tabCashToDebitFromUser,
originatorType: options.eventId ? 'event' : 'content',
originatorId: options.eventId ? options.eventId : newContent.id,
},
{
transaction: options.transaction,
withBalance: true,
},
);

if (balanceResult.total < 0) {
throw new UnprocessableEntityError({
message: `Não foi possível criar a publicação.`,
action: `Você precisa de pelo menos ${Math.abs(tabCashToDebitFromUser)} TabCash para realizar esta ação.`,
errorLocationCode: 'MODEL:CONTENT:UPDATE_TABCASH:NOT_ENOUGH',
});
}
}

async function update(contentId, postedContent, options = {}) {
const validPostedContent = validateUpdateSchema(postedContent);

Expand Down Expand Up @@ -674,6 +718,7 @@ async function update(contentId, postedContent, options = {}) {
updated_content.title,
updated_content.body,
updated_content.status,
updated_content.type,
updated_content.source_url,
updated_content.created_at,
updated_content.updated_at,
Expand Down
11 changes: 11 additions & 0 deletions models/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,16 @@ const schemas = {
});
},

content_type: function () {
return Joi.object({
type: Joi.string()
.trim()
.valid('content', 'ad')
.default('content')
.when('$required.content_type', { is: 'required', then: Joi.required(), otherwise: Joi.optional() }),
});
},

source_url: function () {
return Joi.object({
source_url: Joi.string()
Expand Down Expand Up @@ -482,6 +492,7 @@ const schemas = {
'title',
'body',
'status',
'content_type',
'source_url',
'created_at',
'updated_at',
Expand Down
1 change: 1 addition & 0 deletions pages/api/v1/contents/index.public.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ function postValidationHandler(request, response, next) {
title: 'optional',
body: 'required',
status: 'optional',
content_type: 'optional',
source_url: 'optional',
});

Expand Down
1 change: 1 addition & 0 deletions tests/constants-for-tests.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export const defaultTabCashForAdCreation = 100;
export const maxSlugLength = 160;
export const maxTitleLength = 255;
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
tabcoins_credit: 0,
tabcoins_debit: 0,
status: childBranchBLevel1.status,
type: 'content',
source_url: childBranchBLevel1.source_url,
created_at: childBranchBLevel1.created_at.toISOString(),
updated_at: childBranchBLevel1.updated_at.toISOString(),
Expand All @@ -172,6 +173,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
tabcoins_credit: 0,
tabcoins_debit: 0,
status: childBranchBLevel2Content1.status,
type: 'content',
source_url: childBranchBLevel2Content1.source_url,
created_at: childBranchBLevel2Content1.created_at.toISOString(),
updated_at: childBranchBLevel2Content1.updated_at.toISOString(),
Expand All @@ -192,6 +194,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
tabcoins_credit: 0,
tabcoins_debit: 0,
status: childBranchBLevel2Content2.status,
type: 'content',
source_url: childBranchBLevel2Content2.source_url,
created_at: childBranchBLevel2Content2.created_at.toISOString(),
updated_at: childBranchBLevel2Content2.updated_at.toISOString(),
Expand All @@ -212,6 +215,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
title: childBranchALevel1.title,
body: childBranchALevel1.body,
status: childBranchALevel1.status,
type: 'content',
tabcoins: 1,
tabcoins_credit: 0,
tabcoins_debit: 0,
Expand All @@ -230,6 +234,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
title: childBranchALevel2.title,
body: childBranchALevel2.body,
status: childBranchALevel2.status,
type: 'content',
tabcoins: 1,
tabcoins_credit: 0,
tabcoins_debit: 0,
Expand All @@ -251,6 +256,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
tabcoins_credit: 0,
tabcoins_debit: 0,
status: childBranchALevel3.status,
type: 'content',
source_url: childBranchALevel3.source_url,
created_at: childBranchALevel3.created_at.toISOString(),
updated_at: childBranchALevel3.updated_at.toISOString(),
Expand Down Expand Up @@ -346,6 +352,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
title: childBranchBLevel2Content2.title,
body: childBranchBLevel2Content2.body,
status: childBranchBLevel2Content2.status,
type: 'content',
tabcoins: 1,
tabcoins_credit: 0,
tabcoins_debit: 0,
Expand All @@ -366,6 +373,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
title: childBranchBLevel2Content1.title,
body: childBranchBLevel2Content1.body,
status: childBranchBLevel2Content1.status,
type: 'content',
tabcoins: 0,
tabcoins_credit: 0,
tabcoins_debit: 0,
Expand Down Expand Up @@ -436,6 +444,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
tabcoins_credit: 2,
tabcoins_debit: -1,
status: childBranchBLevel1.status,
type: 'content',
source_url: childBranchBLevel1.source_url,
created_at: childBranchBLevel1.created_at.toISOString(),
updated_at: childBranchBLevel1.updated_at.toISOString(),
Expand All @@ -453,6 +462,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
title: childBranchALevel1.title,
body: childBranchALevel1.body,
status: childBranchALevel1.status,
type: 'content',
tabcoins: 1,
tabcoins_credit: 0,
tabcoins_debit: 0,
Expand All @@ -471,6 +481,7 @@ describe('GET /api/v1/contents/[username]/[slug]/children', () => {
title: childBranchALevel2.title,
body: childBranchALevel2.body,
status: childBranchALevel2.status,
type: 'content',
tabcoins: 5,
tabcoins_credit: 4,
tabcoins_debit: 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ describe('GET /api/v1/contents/[username]/[slug]', () => {
title: 'Conteúdo publicamente disponível',
body: 'Conteúdo relevante deveria estar disponível para todos.',
status: 'published',
type: 'content',
tabcoins: 1,
tabcoins_credit: 0,
tabcoins_debit: 0,
Expand Down Expand Up @@ -203,6 +204,7 @@ describe('GET /api/v1/contents/[username]/[slug]', () => {
title: 'Conteúdo root',
body: 'Body with relevant texts needs to contain a good amount of words',
status: 'published',
type: 'content',
tabcoins: 1,
tabcoins_credit: 0,
tabcoins_debit: 0,
Expand Down Expand Up @@ -285,6 +287,7 @@ describe('GET /api/v1/contents/[username]/[slug]', () => {
title: null,
body: 'Conteúdo child',
status: 'published',
type: 'content',
tabcoins: 0,
tabcoins_credit: 0,
tabcoins_debit: 0,
Expand Down Expand Up @@ -355,6 +358,7 @@ describe('GET /api/v1/contents/[username]/[slug]', () => {
title: null,
body: 'Conteúdo child',
status: 'published',
type: 'content',
tabcoins: 0,
tabcoins_credit: 0,
tabcoins_debit: 0,
Expand Down Expand Up @@ -441,6 +445,7 @@ describe('GET /api/v1/contents/[username]/[slug]', () => {
title: 'Conteúdo com TabCoins',
body: 'Conteúdo que foi avaliado positiva e negativamente.',
status: 'published',
type: 'content',
tabcoins: 2,
tabcoins_credit: 3,
tabcoins_debit: -1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ describe('GET /api/v1/contents/[username]/[slug]/parent', () => {
body: 'Root - Body with relevant texts needs to contain a good amount of words',
children_deep_count: 1,
status: 'published',
type: 'content',
source_url: null,
published_at: rootContent.published_at.toISOString(),
created_at: rootContent.created_at.toISOString(),
Expand Down Expand Up @@ -287,6 +288,7 @@ describe('GET /api/v1/contents/[username]/[slug]/parent', () => {
body: 'Child content body Level 2 - relevant content',
children_deep_count: 1,
status: 'published',
type: 'content',
source_url: null,
published_at: childContentLevel2.published_at.toISOString(),
created_at: childContentLevel2.created_at.toISOString(),
Expand Down Expand Up @@ -354,6 +356,7 @@ describe('GET /api/v1/contents/[username]/[slug]/parent', () => {
body: '[Não disponível]',
children_deep_count: 0,
status: 'draft',
type: 'content',
source_url: null,
published_at: null,
created_at: childContentLevel2.created_at.toISOString(),
Expand Down Expand Up @@ -422,6 +425,7 @@ describe('GET /api/v1/contents/[username]/[slug]/parent', () => {
body: '[Não disponível]',
children_deep_count: 0,
status: 'deleted',
type: 'content',
source_url: null,
published_at: childContentLevel2.published_at.toISOString(),
created_at: childContentLevel2.created_at.toISOString(),
Expand Down Expand Up @@ -472,6 +476,7 @@ describe('GET /api/v1/contents/[username]/[slug]/parent', () => {
body: 'Root - Body with relevant texts needs to contain a good amount of words',
children_deep_count: 1,
status: 'published',
type: 'content',
source_url: null,
published_at: rootContent.published_at.toISOString(),
created_at: rootContent.created_at.toISOString(),
Expand Down
Loading
Loading