Commit Graph

882 Commits

Author SHA1 Message Date
Kevin Ansfield
021cfecb59
Fixed __GHOST_URL__ appearing in settings values after edit (#12738)
refs https://github.com/TryGhost/Ghost/pull/12736
refs https://github.com/TryGhost/Team/issues/467

knex's `parse()` method is only called on data when directly fetched from the db. This was causing problems when model instances are passed around via events for example because `.get('key')` will return data that was directly set on the model without having gone through the `parse()` transformations. The result of this inconsistency was settings appearing correct when Ghost started up but then being broken as soon as a setting was changed.

- moved absolute/relative->transform-ready URL transformations from the API input serializers to the model's `format()` method and replaced with a relative->absolute transform in API input serializers
    - results in consistency because `.get()` on a settings model will always return an URL
- removed transform-ready->absolute transforms from the API output serializers as that is now handled at the model-layer
2021-03-08 18:41:43 +00:00
Kevin Ansfield
28f0bc6bd2
Fixed settings images (cover_image, logo, etc) having wrong URL (#12736)
refs https://github.com/TryGhost/Team/issues/467
refs https://github.com/TryGhost/Ghost/pull/12731

- settings are mostly fetched directly from the settings cache rather than via the API so they aren't subject to the API-level output serializers that transform URLs meaning that URLs in the front-end ended up with raw `__GHOST_URL__` replacement strings
- added images to the Settings model's `parse()` method so they are transformed immediately when fetching from the database
2021-03-06 09:00:18 +00:00
Kevin Ansfield
a6f5eb71be
🏗 Changed internal URL storage format to use __GHOST_URL__ (#12731)
closes https://github.com/TryGhost/Team/issues/467

- switches to storing "transform-ready" URLs in the database
- transform-ready URLs contain a `__GHOST_URL__` placeholder that corresponds to the configured url that gives a few benefits
  - much faster and less memory intensive output transformations through not needing to parse html or markdown - the transform can be achieved using a straightforward regex find+replace
  - ability to change to/from or rename subdirectory without any manual updates to the database
- modified existing 4.0 url-transformation migration rather than adding another one and repeating the transformation on posts rows
2021-03-05 13:54:01 +00:00
Hannah Wolfe
d51fcd072e Added new member limit & removed old
refs: https://github.com/TryGhost/Team/issues/510

- The current member limit was implemented as a member-specific concept
- The new limit service is much more generic, here we are swapping old for new
- The updated concept here is blocking all publishing, not just email sending, when a site is over its member limit
- To determine that we are publishing a post, we must be in the model layer. The code has been moved to the permissible function which makes sense as this is a permissions error that we are throwing
- I've left the extra check for email retries in, in case there is some loophole here (but we may wish to change it)
2021-03-04 18:16:34 +00:00
Hannah Wolfe
e30b9735fa Added staff user limit
refs: https://github.com/TryGhost/Team/issues/510

- In the case that host config is provided, keep staff users within the limiti
- The definition of a staff user is a user with a role other than Contributor, and whose status is not inactive
   - Contributors don't count
   - Suspended (status inactive) users don't count
   - Locked users DO count
   - Invited users DO count
- You can't invite more staff users whilst there are pending invites
- You can't unsuspend a user, or change the role on a user in such a way as will take you over your limit
- You can't import staff users - all imported users are automatically set to Contributors
- As part of this work, we are changing the default Ghost user to a Contributor otherwise it uses up a staff user

Note: there is one known active bug with this commit.
- Assume you have one remaining user within your limit. You send an invite, this works.
- You cannot "resend" that invite, it will think you're sending a new invite and hit the limit
- You must "revoke" that invite first, and create a new one
- This bug exists because the resend function uses the add endpoint & does a delete+add, but this hits the permission check before the delete
2021-03-04 16:13:04 +00:00
Hannah Wolfe
26f56626ce Updated host config to correctly use camelCase
refs https://github.com/TryGhost/Team/issues/510

- When the host config was introduced it was incorrectly introduced as host_settings instead of hostSettings
- All other Ghost config uses camelCase, so changing this now before it becomes a problem
- Note: Also removed some rogue return awaits that don't make sense. It's not possible to hit that case, but cleaning up anyway
2021-03-04 11:39:32 +00:00
Hannah Wolfe
edb626af18 Added custom integration feature limit
refs: https://github.com/TryGhost/Team/issues/510

- in the case that host config is provided, prevents the creation of custom integrations
2021-03-03 20:15:49 +00:00
Naz
72f25a7099 Bumped webhook API defaults to v4
refs https://github.com/TryGhost/Ghost/issues/12716

- The default API in Ghost v4 will be `'v4'`. When a new webhook is created or any data passes through serialization it should assume `v4` as a fallback if not specified.
2021-03-02 12:31:52 +13:00
Hannah Wolfe
7f29bbff8a Removed unused add/edit methods from integrations
refs 17feb14e4a

- The original commit adding this intended to add transactions, following the pattern of always forcing a transaction when we use bookshelf-relations
- (We use bookshelf-relations here because integrations have api-keys and webhooks associated wtih them and we upsert as one)
- These add and edit methods were inadvertently added to the wrong argument object/section of bookshelf (really fucking easily done, one day we will fix bookshelf so its easier to work with)
- Bottom line: these methods have never been called
- I tried moving them to the right section, but this created test failures throughout our acceptance tests:
   - Error: Transaction query already complete, run with DEBUG=knex:tx for more info
- This is likely because we need to account for integrations being used as part of the auth step in the before part of tests
- In terms of yak-shaving, fixing these tests is one step too far right now. I think not having this code here at all is a better state than having it look like it works when it doesn't
2021-02-25 10:48:05 +00:00
Fabien 'egg' O'Carroll
714e081efc
Removed hardcoded currency symbols (#12700)
refs https://github.com/TryGhost/Team/issues/473
refs https://github.com/TryGhost/Admin/commit/638e5027

We no longer want to maintain a list of currency symbols now that we support 100+ currencies,
so we will be relying on the `{{price}}` helper in themes and `Intl.NumberFormat` elsewhere.
2021-02-25 09:49:07 +00:00
Rish
6d2b731379 Fixed member status events query
refs https://github.com/TryGhost/Ghost/issues/12602

- Adds aggregate option to permitted options
- Cleans up SQL query to fetch delta values
2021-02-18 18:11:50 +05:30
Kevin Ansfield
2c96df42ac
Added paywall card to mark end of free content preview (#12663)
closes https://github.com/TryGhost/Team/issues/466

- upgraded kg-default-cards to include paywall card
- extracted `htmlToPlaintext` from post model to shared util for re-use
- updated post-gating to set html+plaintext to the free preview if a paywall card has been used
  - re-generates plaintext from the truncated html using `htmlToPlaintext` util
- display free content in the `{{content}}` helper via the default CTA template
2021-02-17 23:00:26 +00:00
Fabien 'egg' O'Carroll
27b9e4ae04
Added member relation to events (#12656)
refs https://github.com/TryGhost/Ghost/issues/12602

When listing site-wide event, we want to include member information so
that we can contextualise the event when displaying it.
2021-02-16 16:14:20 +00:00
Fabien 'egg' O'Carroll
f4cb5c57c6
Updated members_status_events table (#12647)
refs https://github.com/TryGhost/Ghost/issues/12602

* Updated members_status_events table

By replacing the `status` column with a `from_status` and `to_status`
column, we are able to track the changes between multiple statuses
easier, and accumulate the data. e.g. the delta of paid members in a
given time range is the sum of the `to_status` columns set to 'paid'
minus the sum of the `from_status` columns set to 'paid' within that
time range

* Updated MEGA to handle addition of 'comped' status

With the addition of the 'comped' status, we need to ensure that MEGA
will still send emails to the correct recipients. I've opted to use an
"inverse" filter, as that is the intention of the free/paid split in
MEGA - as far as MEGA is concerned, "free" is the opposite of "paid"

* Updated customQuery for MemberStatusEvent

With the `status` column replaced with `from_status` and `to_status`
this allows us to fix and update the customQuery to correctly accumulate
the data into deltas over time, broken down by day.

* Populated members_status_events table

As the table will be used to generate deltas, we need to backfill the
data so that existing sites will be able to sum up the deltas and
calculate correct data.

The assumptions used in backfilling is that a Member's current status,
is their only status.
2021-02-16 10:38:36 +00:00
Rish
964fe222be Fixed incorrect volume delta selection in query
refs https://github.com/TryGhost/Ghost/issues/12602

The gross volume aggregate query was incorrectly naming the selected `SUM(amount)` value as `gross_volume` instead of expected `volume_delta`
2021-02-16 11:18:58 +05:30
Fabien O'Carroll
b5c1b9e4fa Added customQuery for MemberStatusEvent
refs https://github.com/TryGhost/Ghost/issues/12602

This allows us to build up a count of member statuses over time
2021-02-12 16:38:57 +00:00
Fabien O'Carroll
7cf0252392 Added MemberPaidSubscriptionEvent model
refs https://github.com/TryGhost/Ghost/issues/12602

- Adds the aggregateMRRDeltas option to the `findAll` method,
allowing us to calculate MRR over time
2021-02-12 13:55:14 +00:00
Fabien O'Carroll
a68d037cef Added MemberEmailChangeEvent model
refs https://github.com/TryGhost/Ghost/issues/12602
2021-02-12 13:55:14 +00:00
Fabien O'Carroll
8e7d11ce40 Added MemberLoginEvent model
refs https://github.com/TryGhost/Ghost/issues/12602
2021-02-12 13:55:14 +00:00
Fabien O'Carroll
a8ee271336 Added MemberPaymentEvent model
refs https://github.com/TryGhost/Ghost/issues/12602

- Adds the aggregatePaymentVolume option to the `findAll` method,
allowing us to calculate volume over time
2021-02-12 13:55:14 +00:00
Fabien O'Carroll
1af6be63f0 Added MemberStatusEvent model
refs https://github.com/TryGhost/Ghost/issues/12602
2021-02-12 13:55:14 +00:00
Fabien O'Carroll
4dd1423026 Added missing semicolon
no-issue
2021-02-10 10:14:29 +00:00
Fabien O'Carroll
9a142cd906 Added aggregateSubscriptionDeltas to permitted options
no-issue

This was missing from https://github.com/TryGhost/Ghost/commit/1dc6fdc.
Without it the option will never be passed into the customQuery method.
2021-02-10 10:06:06 +00:00
Fabien O'Carroll
93b1035df5 🐛 Fixed Member model removing labels when unset
closes https://github.com/TryGhost/Ghost/issues/12600

The bookshelf-relations plugin which we use will **remove** all
relations when they are set to an empty array, but will leave them alone
if it's set to undefined.

Our logic to deduplicate uppercase & lowercase version of the same label
was in advertently always setting the labels to an array, but when the
model was saved without passing the labels, this array would be empty.

Here we've added a check which will skip all label handling, if there
are no labels set.
2021-02-08 09:39:46 +00:00
Fabien O'Carroll
1dc6fdcd66 Added customQuery to handle subscribed aggregates
refs https://github.com/TryGhost/Ghost/issues/12602

In order to build up a list of un/subscribes over time we have to use
the customQuery functionality to run SQL aggregates - this is "hidden"
behind an option, so that we can find{All,Page} as usual.
2021-02-05 16:02:08 +00:00
Fabien O'Carroll
5aab41931f Added skeleton MemberSubscribeEvent model
refs https://github.com/TryGhost/Ghost/issues/12602

Member Events in general are read-only after they've been created, so
we've explicitly disallowed destroying and editing via the model
2021-02-05 16:02:08 +00:00
Naz
6b61bcf123 Added unique constraint notation to schema definition
refs https://github.com/TryGhost/Ghost/issues/12567

- Introduced here @@UNIQUE_CONSTRAINTS@@ notation allows to create unique contraints over multiple database fields. This will be needed to change posts' table unique constraint from `slug` to `slug+type`.
- The notation is equivalent to SQL's: UNIQUE(column_name1,column_name2)
- Example use in schema:
posts: {
    slug: {type: 'string', maxlength: 191, nullable: false},
    type: {type: 'string', maxlength: 50, nullable: false, defaultTo: 'post', validations: {isIn: [['post', 'page']]}},
    '@@UNIQUES@@': [
        ['slug', 'type']
    ]
}
2021-02-04 13:37:20 +13:00
Kevin Ansfield
7195a904ba Fixed settings validation error not distinguishing between publishable/secret keys
no issue

- when saving Stripe keys with `stripeDirect: true` config, if either key didn't match the key format the returned validation error always contained `stripe_secret_key`
- updated to output `stripe_publishable_key` if it was the publishable key that was invalid
2021-02-03 16:42:51 +00:00
Fabien 'egg' O'Carroll
73f6fd8c51
Enabled Members for all sites (#12582)
no-issue

This removes all references to the members labs setting, any code that was run conditionally behind this flag now runs unconditionally. 

* Removed usage of Members labs flag
* Removed tests for Members disabled
* Added dynamic keypair generation for when setting is missing
2021-02-02 16:12:53 +00:00
Rishabh Garg
26ee648397
🏗 Flattened members subscriptions data in API (#12581)
no refs

- Updates member model serializer to directly set subscriptions on member object instead of `stripe.subscriptions`
- Updates all references to members subscriptions from nested `stripe.subscriptions` to `subscriptions`
- Updates v3 API serializer to still use `stripe.subscriptions`
- Updates tests
2021-02-02 16:12:53 +00:00
Fabien 'egg' O'Carroll
6af2706f10
Updated Admin API and Mega to use status flag (#12579)
no-issue

* Removed support for paid param from v3 & canary API
* Updated active subscription checks to use status flag
* Updated MEGA to use status filter over paid flag
* Removed support for paid option at model level
* Installed @tryghost/members-api@1.0.0-rc.0
* Updated members fixtures
2021-02-02 16:12:51 +00:00
Fabien 'egg' O'Carroll
a79ed1170d
Added status property to members (#12570)
refs #12160

This flag will allow us easier filtering of members via the API

* Added status column to members table

This flag will be used to determine if a member is free or paid, rather
than relying on joins with the customers and subscriptions tables.

* Added migration to populate members.status

As we add the column with a default value of "free" we only need to care
about the paid members here. We also preemptively handle migrations for
SQLite where there are > 998 paid members.
2021-02-02 16:11:34 +00:00
Aileen Nowak
c9d1fa0b96 Updated links to ghost.org sites
no issue

Follow-up task of the updated Ghost Docs structure. Updated links reflecting the new structure to prevent unnecessary 404s and redirects.
2021-01-20 09:59:45 +13:00
Fabien 'egg' O'Carroll
7fdddf34b3
🐛 Added multiple use grace period to tokens (#12519)
closes https://github.com/TryGhost/Ghost/issues/12347

This change allows a token to be used multiple times for the first 10
seconds after its initial use, this will stop dynamic link checking
software from invaliding magic links.
2021-01-18 17:03:41 +00:00
Kevin Ansfield
93fa9b4d9e Removed unnecessary bookshelf-relations config in EmailRecipient model
no issue

- we don't use any of the `bookshelf-relations` plugin's added features for the `EmailRecipient` model so there's no need to opt in to it
2021-01-05 15:28:30 +00:00
Kevin Ansfield
eccd220461 🐛 Fixed error when deleting a member that has received a newsletter email
closes https://github.com/TryGhost/Ghost/issues/12493

- bumps `bookshelf-relations` to new version that allows for `hasMany` children to be kept when a parent record is destroyed
- adds necessary config to the `Member.email_recipients` relationship to keep related records when a member is deleted
2021-01-05 14:06:20 +00:00
Sumedh
e756af65f2 Removed invalid default 'core' value in settings type
closes #12181
refs https://github.com/TryGhost/Ghost/pull/12265

- The 'core' value is invalid for settings 'type' column
- The 'core' default value for 'type' column in model is also invalid
- Both need to be removed as they are never used and only introduce confusion into the codebase
2021-01-04 15:32:57 +13:00
Kevin Ansfield
8aa55feaf8
Added acceptance test for /member/:id/?include=email_recipients (#12477)
refs c1d66f0b01

- fixed base model allowing '@@INDEXES@@' as a permitted attribute/order
- fixed base model automatically setting `@@INDEXES@@` to null on the model when creating
- added `doAuth('members:emails')`
  - creates an `email_batch` record attached to the first email in the fixtures
  - creates an `email_recipients` record for each member
  - runs analytics aggregation so the email and member counts are as expected
- added acceptance test for `/member/:id/?include=email_recipients`
2020-12-11 18:45:35 +00:00
Kevin Ansfield
c1d66f0b01
Added email_recipients include option to members API read endpoint (#12471)
refs https://github.com/TryGhost/Ghost-Admin/pull/1796

We want to be able to display an email activity timeline in Ghost-Admin for each member. The quickest way to achieve that right now is to provide access to the `email_recipient` data for the member when fetching, this will allow clients to build up a timeline based on the event timestamps included with each email_recipient/email pair.

- sets up `email_recipients` relationship in `Member` model
- updates members API read endpoint to accept an `email_recipients` include parameter
  - appends `email_recipients.email` to the `withRelated` array when `email_recipients` is included so that we have data available for email subject and html/plaintext for previews
- updates members API output serializer to include the email_recipients object in the output
2020-12-10 10:04:05 +00:00
Kevin Ansfield
b1aafd715d
Added members.email_{count,opened_count} column migrations (#12470)
refs https://github.com/TryGhost/Ghost/issues/12461

- adds `members.email_count` and `members.email_opened_count` columns to contain cached counts for faster queries when outputting member data via API
- adds migration to populate cached counts with existing data
  - tested locally on ~50k members which took ~4sec on mysql
- updates members output serializer to include the new fields in API output
2020-12-09 12:21:56 +00:00
Kevin Ansfield
748a8e0d0f
Added email_open_rate order option to members API (#12462)
refs https://github.com/TryGhost/Ghost/issues/12421

- add `orderRawQuery` function to members model so that we can ensure members with an open rate are ordered before members without an open rate no matter the order direction chosen
- added `email_open_rate` to members in the test fixtures to allow testing of order
2020-12-08 12:43:48 +00:00
Kevin Ansfield
7c57ffd6a6 Fixed posts without open rate being ordered in reverse
refs https://github.com/TryGhost/Ghost/issues/12420

- adds additional sorting by post creation date so that posts below those with an open rate appear in a more useful order
2020-12-04 13:12:14 +00:00
Kevin Ansfield
9ff7423b2b
Added email.open_rate order option to posts api (#12439)
refs https://github.com/TryGhost/Ghost/issues/12420

- updated `order` bookshelf plugin's `parseOrderOption()` method to return multiple order-related properties
  - `order` same as before, a key-value object of property-direction
  - `orderRaw` new property that is a raw SQL order string generated from `orderRawQuery()` method in models
  - `eagerLoad` new property that is an array of properties the `eagerLoad` plugin should use to join across
- updated `pagination.fetchAll()` to apply normal order + raw order if both are available and to handle eager loading / joins when `options.eagerLoad` is populated
- updated post model to include details for email relationship and to add `orderRawQuery()` that allows `email.open_rate` to be used as an order option
2020-12-03 20:13:37 +00:00
Kevin Ansfield
0c59b948fa
Added migrations for email analytics (#12387)
no issue

- cleans up unused tables `emails.{meta,stats}`
- adds timestamp columns `email_recipients.{delivered_at,opened_at,failed_at}` that can be used for event timelines and basic stats aggregation
  - indexed because we want to sort by these columns to find the "latest event" when limiting Mailgun events API requests
- adds aggregated stats columns `emails.{delivered_count,opened_count,failed_count}`
- adds a composite index on `email_recipients.[email_id,member_email]` to dramatically speed up `email_recipient` update queries when processing events
  - modifies the db initialisation to support an `'@@INDEXES@@'` key in table schema definition for composite indexes
2020-11-25 17:48:24 +00:00
Fabien 'egg' O'Carroll
18b87d9734
Included all subscriptions in stripeSubscriptions (#12414)
refs https://github.com/TryGhost/Ghost/issues/12256

We no longer want to filter out cancelled subscriptions, so we are able
to remove the whereIn clause of the relation.

* Fixed paid flag on member
* Fixed content gating for members

Now that the subscriptions for a member include all of them, we must
explicitly check that the member has an active subscription in order to
consider them "paid"
2020-11-25 10:39:07 +00:00
Fabien 'egg' O'Carroll
217f069085
Included cancellation_reason in subscription serialization (#12411)
refs #12403 

This new property needed to be exposed in serialization so that Ghost-Admin
can use it via the API.
2020-11-23 21:19:27 +00:00
Thibaut Patel
214ed405cc Added the user_id field to the api_keys table
no issue

- Migration related to the Personal Tokens feature.
2020-11-20 09:53:18 +01:00
Fabien 'egg' O'Carroll
bfc152bede
Fixed handling of email_recipient_filter option (#12369)
no-issue

This logic would assume that the option was always passed at the point
of publishing the post, which is not the case for scheduled posts.

Instead of setting the property to 'none' when the option is not
present, we take the approach of ONLY setting the propery when
1. It is present and not 'none'
2. The post is being published or scheduled

This means that scheduled posts will have the property set correctly,
and any future publishing will leave the it in the original state
2020-11-17 11:00:03 +00:00
Fabien 'egg' O'Carroll
4604ba1587
Fixed backward compatibility for send_email_when_published (#12357)
no-issue

* Handled send_email_when_published in Posts API

This restores backwards compatibility of the Posts API allowing existing
clients to continue to use the `send_email_when_published` flag. This
change uses two edits, which is unfortunate. The reason being is that
this is an API compatibility issue, not a model issue, so we shouldn't
introduce code to the model layer to handle it. The visibility property
of the model is used to determine how to fall back, and because it can
be left out of the API request, and relies on a default in the settings,
we require that the model decide on the `visibility` before we run our
fallback logic (or we duplicate the `visibility` default at the cost of
maintenance in the future)

* Dropped send_email_when_published column from posts

Since this column is not used any more, we can drop it from the table.
We include an extra migration to repopulate the column in the event of
a rollback

* Updated importer to handle send_email_when_published

Because we currently export this value from Ghost, we should correctly
import it. This follows the same logic as the migrations for this value.

* Included send_email_when_published in API response

As our v3 API documentation includes `send_email_when_published` we must
retain backward compatibility by calculating the property.

* Fixed fields filter with send_email_when_published

* Added safety checks to frame properties

Some parts of the code pass a manually created "frame" which is missing
lots of properties, so we check for the existence of all of them before
using them.

* Fixed 3.1 migration to include columnDefinition

We require that migrations have all the information they need contained
within them as they run in an unknown state of the codebase, which could
be from the commit they are introduced, to any future commit. In this
case the column definition is removed from the schema in 3.38 and the
migration would fail when run in this version or later.
2020-11-11 13:03:41 +00:00
Fabien 'egg' O'Carroll
6140a98351
Updated newsletter functionality to use email_recipient_filter (#12343)
no-issue

* Used email_recipient_filter in MEGA

This officially decouples the newsletter recipients from the post
visibility allowing us to send emails to free members only

* Supported enum for send_email_when_published in model

This allows us to migrate from the previously used boolean to an enum
when we eventually rename the email_recipient_filter column to
send_email_when_published

* Updated the posts API to handle email_recipient_filter

We now no longer rely on the send_email_when_published property to send
newsletters, meaning we can remove the column and start cleaning up the
new columns name

* Handled draft status changes when emails not sent

We want to reset any concept of sending an email when a post is
transition to the draft status, if and only if, and email has not
already been sent. If an email has been sent, we should leave the email
related fields as they were.

* Removed send_email_when_published from add method

This is not supported at the model layer

* Removed email_recipient_filter from v2&Content API

This should not be exposed on previous api versions, or publicly

* Removed reference to send_email_when_published

This allows us to move completely to the email_recipient_filter
property, keeping the code clean and allowing us to delete the
send_email_when_published column in the database. We plan to then
migrate _back_ to the send_email_when_published name at both the
database and api level.
2020-11-06 17:32:23 +00:00