@ozguraltan/strapi-content-input 1.0.23 → 1.0.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1970,6 +1970,79 @@ const ciSurveyController = ({ strapi }) => ({
1970
1970
  } catch (err) {
1971
1971
  ctx.throw(500, err);
1972
1972
  }
1973
+ },
1974
+ async purgeDemo(ctx) {
1975
+ try {
1976
+ const res = await strapi.plugin("content-input").service("ci-survey").purgeDemoData();
1977
+ ctx.status = 200;
1978
+ ctx.body = res;
1979
+ } catch (err) {
1980
+ ctx.throw(500, err);
1981
+ }
1982
+ },
1983
+ async clearResponses(ctx) {
1984
+ try {
1985
+ const { id } = ctx.params;
1986
+ const res = await strapi.plugin("content-input").service("ci-survey").clearResponses(id);
1987
+ if (!res) {
1988
+ return ctx.notFound("Survey not found");
1989
+ }
1990
+ ctx.status = 200;
1991
+ ctx.body = res;
1992
+ } catch (err) {
1993
+ ctx.throw(500, err);
1994
+ }
1995
+ },
1996
+ async exportBundle(ctx) {
1997
+ try {
1998
+ const target = String(ctx.query?.target || "all").trim();
1999
+ const rawMode = String(ctx.query?.mode || "structure").trim().toLowerCase();
2000
+ const mode = rawMode === "full" ? "full" : "structure";
2001
+ const directDownload = String(ctx.query?.download || "") === "1";
2002
+ const exported = await strapi.plugin("content-input").service("ci-survey").exportBundle(target, mode);
2003
+ if (!exported) {
2004
+ return ctx.notFound("Survey not found");
2005
+ }
2006
+ if (directDownload) {
2007
+ ctx.body = JSON.stringify(exported.bundle, null, 2);
2008
+ ctx.type = exported.contentType;
2009
+ ctx.set("Content-Type", exported.contentType);
2010
+ ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
2011
+ ctx.status = 200;
2012
+ return;
2013
+ }
2014
+ ctx.status = 200;
2015
+ ctx.body = {
2016
+ filename: exported.filename,
2017
+ bundle: exported.bundle
2018
+ };
2019
+ } catch (err) {
2020
+ ctx.throw(500, err);
2021
+ }
2022
+ },
2023
+ async importBundle(ctx) {
2024
+ try {
2025
+ const rawBody = ctx.request.body || {};
2026
+ const hasEnvelope = rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) && rawBody.bundle !== void 0;
2027
+ const bundlePayload = hasEnvelope ? rawBody.bundle : rawBody;
2028
+ const rawStrategy = String(
2029
+ (hasEnvelope ? rawBody.conflictStrategy : ctx.query?.conflictStrategy) || "duplicate"
2030
+ ).trim().toLowerCase();
2031
+ const conflictStrategy = rawStrategy === "overwrite" ? "overwrite" : "duplicate";
2032
+ const rawInclude = hasEnvelope ? rawBody.includeResponses : ctx.query?.includeResponses;
2033
+ const includeResponses = rawInclude === void 0 ? true : rawInclude !== false && String(rawInclude).toLowerCase() !== "false";
2034
+ const res = await strapi.plugin("content-input").service("ci-survey").importBundle(bundlePayload, {
2035
+ conflictStrategy,
2036
+ includeResponses
2037
+ });
2038
+ ctx.status = 200;
2039
+ ctx.body = res;
2040
+ } catch (err) {
2041
+ if (err?.status === 400) {
2042
+ return ctx.badRequest(err.message || "Invalid survey bundle");
2043
+ }
2044
+ ctx.throw(500, err);
2045
+ }
1973
2046
  }
1974
2047
  });
1975
2048
  const ciColorController = ({ strapi }) => ({
@@ -2283,6 +2356,46 @@ const routes = {
2283
2356
  policies: []
2284
2357
  }
2285
2358
  },
2359
+ {
2360
+ method: "POST",
2361
+ path: "/surveys/purge-demo",
2362
+ handler: "ci-survey.purgeDemo",
2363
+ config: {
2364
+ policies: []
2365
+ }
2366
+ },
2367
+ {
2368
+ method: "GET",
2369
+ path: "/survey-bundle/export",
2370
+ handler: "ci-survey.exportBundle",
2371
+ config: {
2372
+ policies: []
2373
+ }
2374
+ },
2375
+ {
2376
+ method: "POST",
2377
+ path: "/survey-bundle/import",
2378
+ handler: "ci-survey.importBundle",
2379
+ config: {
2380
+ policies: []
2381
+ }
2382
+ },
2383
+ {
2384
+ method: "GET",
2385
+ path: "/surveys/bundle/export",
2386
+ handler: "ci-survey.exportBundle",
2387
+ config: {
2388
+ policies: []
2389
+ }
2390
+ },
2391
+ {
2392
+ method: "POST",
2393
+ path: "/surveys/bundle/import",
2394
+ handler: "ci-survey.importBundle",
2395
+ config: {
2396
+ policies: []
2397
+ }
2398
+ },
2286
2399
  {
2287
2400
  method: "POST",
2288
2401
  path: "/surveys",
@@ -2307,6 +2420,14 @@ const routes = {
2307
2420
  policies: []
2308
2421
  }
2309
2422
  },
2423
+ {
2424
+ method: "DELETE",
2425
+ path: "/surveys/:id/responses",
2426
+ handler: "ci-survey.clearResponses",
2427
+ config: {
2428
+ policies: []
2429
+ }
2430
+ },
2310
2431
  {
2311
2432
  method: "GET",
2312
2433
  path: "/surveys/:id/analytics",
@@ -4528,6 +4649,84 @@ function generateSampleFormSubmissions(formEntry) {
4528
4649
  }
4529
4650
  return list;
4530
4651
  }
4652
+ const DEMO_SEED_STORE_KEY = "demo_seed_state";
4653
+ const fallbackStore = /* @__PURE__ */ new WeakMap();
4654
+ function isDemoSeedDisabledByEnv() {
4655
+ const raw = String(process.env.CI_DISABLE_DEMO_SEED || "").trim().toLowerCase();
4656
+ return raw === "true" || raw === "1" || raw === "yes";
4657
+ }
4658
+ function getPluginStore(strapi) {
4659
+ if (strapi && typeof strapi.store === "function") {
4660
+ return strapi.store({
4661
+ type: "plugin",
4662
+ name: "content-input"
4663
+ });
4664
+ }
4665
+ return null;
4666
+ }
4667
+ async function getDemoSeedState(strapi) {
4668
+ const disabledByEnv = isDemoSeedDisabledByEnv();
4669
+ let stored = null;
4670
+ try {
4671
+ const store = getPluginStore(strapi);
4672
+ if (store && typeof store.get === "function") {
4673
+ const val = await store.get({ key: DEMO_SEED_STORE_KEY });
4674
+ if (val && typeof val === "object") {
4675
+ stored = val;
4676
+ }
4677
+ } else if (strapi && typeof strapi === "object") {
4678
+ stored = fallbackStore.get(strapi) || null;
4679
+ }
4680
+ } catch {
4681
+ if (strapi && typeof strapi === "object") {
4682
+ stored = fallbackStore.get(strapi) || null;
4683
+ }
4684
+ }
4685
+ return {
4686
+ cleared: Boolean(stored?.cleared),
4687
+ surveysInitialized: Boolean(stored?.surveysInitialized),
4688
+ formsInitialized: Boolean(stored?.formsInitialized),
4689
+ updatedAt: stored?.updatedAt || "",
4690
+ disabledByEnv
4691
+ };
4692
+ }
4693
+ async function updateDemoSeedState(strapi, patch) {
4694
+ const current = await getDemoSeedState(strapi);
4695
+ const next = {
4696
+ cleared: patch.cleared !== void 0 ? Boolean(patch.cleared) : current.cleared,
4697
+ surveysInitialized: patch.surveysInitialized !== void 0 ? Boolean(patch.surveysInitialized) : Boolean(current.surveysInitialized),
4698
+ formsInitialized: patch.formsInitialized !== void 0 ? Boolean(patch.formsInitialized) : Boolean(current.formsInitialized),
4699
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4700
+ };
4701
+ if (strapi && typeof strapi === "object") {
4702
+ fallbackStore.set(strapi, next);
4703
+ }
4704
+ try {
4705
+ const store = getPluginStore(strapi);
4706
+ if (store && typeof store.set === "function") {
4707
+ await store.set({
4708
+ key: DEMO_SEED_STORE_KEY,
4709
+ value: next
4710
+ });
4711
+ }
4712
+ } catch {
4713
+ }
4714
+ return next;
4715
+ }
4716
+ async function isDemoSeedBlocked(strapi, domain) {
4717
+ const state = await getDemoSeedState(strapi);
4718
+ if (state.disabledByEnv || state.cleared) return true;
4719
+ if (domain === "surveys" && state.surveysInitialized) return true;
4720
+ if (domain === "forms" && state.formsInitialized) return true;
4721
+ return false;
4722
+ }
4723
+ async function setDemoSeedCleared(strapi, cleared) {
4724
+ return updateDemoSeedState(strapi, {
4725
+ cleared,
4726
+ surveysInitialized: true,
4727
+ formsInitialized: true
4728
+ });
4729
+ }
4531
4730
  const FORM_UID = "plugin::content-input.ci-form";
4532
4731
  const SUBMISSION_UID = "plugin::content-input.ci-form-submission";
4533
4732
  function slugifyIdentifier$1(text) {
@@ -4545,7 +4744,7 @@ function slugifyIdentifier$1(text) {
4545
4744
  ü: "u",
4546
4745
  Ü: "u"
4547
4746
  };
4548
- return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
4747
+ return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-{2,}/g, "-").replace(/_{2,}/g, "_").replace(/^[-_]+|[-_]+$/g, "");
4549
4748
  }
4550
4749
  function stripHtmlTags(html) {
4551
4750
  return String(html || "").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<[^>]+>/g, " ").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'").replace(/\s+/g, " ").trim();
@@ -4856,11 +5055,20 @@ const ciFormService = ({ strapi }) => ({
4856
5055
  },
4857
5056
  async ensureSampleSubmissions(force = false) {
4858
5057
  try {
5058
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5059
+ return;
5060
+ }
4859
5061
  const subCount = await strapi.db.query(SUBMISSION_UID).count();
4860
5062
  if (subCount > 0 && !force) return;
4861
- const showcaseForm = await strapi.db.query(FORM_UID).findOne({
5063
+ let showcaseForm = await strapi.db.query(FORM_UID).findOne({
4862
5064
  where: { slug: "showcase_contact_form" }
4863
5065
  });
5066
+ if (!showcaseForm && force) {
5067
+ const seedDef = DEFAULT_SEED_FORMS.find((s) => s.slug === "showcase_contact_form");
5068
+ if (seedDef) {
5069
+ showcaseForm = await strapi.db.query(FORM_UID).create({ data: seedDef });
5070
+ }
5071
+ }
4864
5072
  if (!showcaseForm) return;
4865
5073
  if (force) {
4866
5074
  await strapi.db.query(SUBMISSION_UID).deleteMany({
@@ -4874,16 +5082,24 @@ const ciFormService = ({ strapi }) => ({
4874
5082
  } catch {
4875
5083
  }
4876
5084
  },
4877
- async ensureSeeded() {
5085
+ async ensureSeeded(force = false) {
5086
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5087
+ return;
5088
+ }
4878
5089
  let count = 0;
4879
5090
  try {
4880
5091
  count = await strapi.db.query(FORM_UID).count();
4881
5092
  } catch {
4882
5093
  return;
4883
5094
  }
4884
- if (count === 0) {
5095
+ if (count === 0 || force) {
4885
5096
  for (const seed of DEFAULT_SEED_FORMS) {
4886
- await strapi.db.query(FORM_UID).create({ data: seed });
5097
+ const existingSeed = await strapi.db.query(FORM_UID).findOne({
5098
+ where: { slug: seed.slug }
5099
+ });
5100
+ if (!existingSeed) {
5101
+ await strapi.db.query(FORM_UID).create({ data: seed });
5102
+ }
4887
5103
  }
4888
5104
  } else {
4889
5105
  try {
@@ -4902,7 +5118,52 @@ const ciFormService = ({ strapi }) => ({
4902
5118
  } catch {
4903
5119
  }
4904
5120
  }
4905
- await this.ensureSampleSubmissions(false);
5121
+ await this.ensureSampleSubmissions(force);
5122
+ await updateDemoSeedState(strapi, { formsInitialized: true });
5123
+ },
5124
+ async purgeDemoForms() {
5125
+ let deletedForms = 0;
5126
+ let deletedFormSubmissions = 0;
5127
+ const demoSlugs = DEFAULT_SEED_FORMS.map((f) => f.slug);
5128
+ for (const slug of demoSlugs) {
5129
+ try {
5130
+ const existingForm = await strapi.db.query(FORM_UID).findOne({
5131
+ where: { slug }
5132
+ });
5133
+ const matchingSubs = await strapi.db.query(SUBMISSION_UID).findMany({
5134
+ where: existingForm ? {
5135
+ $or: [
5136
+ { formSlug: slug },
5137
+ { formId: String(existingForm.documentId || existingForm.id) },
5138
+ { formId: String(existingForm.id) }
5139
+ ]
5140
+ } : { formSlug: slug }
5141
+ }) || [];
5142
+ if (matchingSubs.length > 0) {
5143
+ const subIds = matchingSubs.map((s) => s.id).filter((id) => id !== void 0 && id !== null);
5144
+ if (subIds.length > 0) {
5145
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
5146
+ where: { id: { $in: subIds } }
5147
+ });
5148
+ }
5149
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
5150
+ where: { formSlug: slug }
5151
+ });
5152
+ deletedFormSubmissions += matchingSubs.length;
5153
+ }
5154
+ if (existingForm) {
5155
+ await strapi.db.query(FORM_UID).delete({
5156
+ where: { id: existingForm.id }
5157
+ });
5158
+ deletedForms += 1;
5159
+ }
5160
+ } catch {
5161
+ }
5162
+ }
5163
+ return {
5164
+ deletedForms,
5165
+ deletedFormSubmissions
5166
+ };
4906
5167
  },
4907
5168
  async findRawByIdOrSlug(idOrSlug) {
4908
5169
  await this.ensureSeeded();
@@ -6115,7 +6376,7 @@ function slugifyIdentifier(text) {
6115
6376
  ü: "u",
6116
6377
  Ü: "u"
6117
6378
  };
6118
- return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
6379
+ return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-{2,}/g, "-").replace(/_{2,}/g, "_").replace(/^[-_]+|[-_]+$/g, "");
6119
6380
  }
6120
6381
  function getEnvRecaptchaPublicKey() {
6121
6382
  return (process.env.MIX_RECAPTCHA_PUBLIC_KEY || process.env.RECAPTCHA_PUBLIC_KEY || process.env.NUXT_PUBLIC_RECAPTCHA_SITE_KEY || "").trim();
@@ -6182,38 +6443,126 @@ function sanitizeSurveyForPublic(entry, extra = {}) {
6182
6443
  publicResults: extra.publicResults || null
6183
6444
  };
6184
6445
  }
6446
+ function sanitizeSurveyForBundle(entry, rawResponses) {
6447
+ const cleanTitle = String(entry?.title || "Untitled Survey").trim();
6448
+ const cleanSlug = String(entry?.slug || slugifyIdentifier(cleanTitle) || "survey").trim();
6449
+ const sortedResponses = Array.isArray(rawResponses) ? [...rawResponses].sort((a, b) => {
6450
+ const ta = new Date(a?.submittedAt || a?.createdAt || 0).getTime();
6451
+ const tb = new Date(b?.submittedAt || b?.createdAt || 0).getTime();
6452
+ return ta - tb;
6453
+ }) : [];
6454
+ return {
6455
+ title: cleanTitle,
6456
+ titleI18n: entry?.titleI18n || { tr: cleanTitle, en: cleanTitle },
6457
+ slug: cleanSlug,
6458
+ description: entry?.description ?? { tr: "", en: "" },
6459
+ status: entry?.status || "published",
6460
+ displayMode: entry?.displayMode || "single_page",
6461
+ startsAt: entry?.startsAt || null,
6462
+ endsAt: entry?.endsAt || null,
6463
+ quotaLimit: entry?.quotaLimit ? Number(entry.quotaLimit) : null,
6464
+ submissionPolicy: entry?.submissionPolicy || "one_per_voter",
6465
+ anonymizeIp: entry?.anonymizeIp !== void 0 ? Boolean(entry.anonymizeIp) : true,
6466
+ showPublicResults: entry?.showPublicResults || "after_vote",
6467
+ allowBackNavigation: entry?.allowBackNavigation !== void 0 ? Boolean(entry.allowBackNavigation) : true,
6468
+ showProgressBar: entry?.showProgressBar !== void 0 ? Boolean(entry.showProgressBar) : true,
6469
+ useRecaptcha: entry?.useRecaptcha !== void 0 ? Boolean(entry.useRecaptcha) : false,
6470
+ recaptchaSiteKey: entry?.recaptchaSiteKey ? String(entry.recaptchaSiteKey) : "",
6471
+ steps: Array.isArray(entry?.steps) ? entry.steps : [],
6472
+ questions: Array.isArray(entry?.questions) ? entry.questions : [],
6473
+ settings: entry?.settings && typeof entry.settings === "object" ? entry.settings : {},
6474
+ version: Number(entry?.version || 1),
6475
+ responses: sortedResponses.map((r) => ({
6476
+ answers: r?.answers && typeof r.answers === "object" && !Array.isArray(r.answers) ? r.answers : {},
6477
+ otherTexts: r?.otherTexts && typeof r.otherTexts === "object" && !Array.isArray(r.otherTexts) ? r.otherTexts : {},
6478
+ score: typeof r?.score === "number" ? r.score : null,
6479
+ npsValue: typeof r?.npsValue === "number" ? r.npsValue : null,
6480
+ npsCategory: r?.npsCategory || null,
6481
+ locale: String(r?.locale || "en"),
6482
+ durationSeconds: Math.max(0, Number(r?.durationSeconds || 0) || 0),
6483
+ voterHash: r?.voterHash || null,
6484
+ respondentToken: r?.respondentToken || null,
6485
+ submittedAt: r?.submittedAt || r?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
6486
+ }))
6487
+ };
6488
+ }
6489
+ function makeUniqueSlug(baseSlug, usedSlugs) {
6490
+ const cleanBase = slugifyIdentifier(baseSlug) || "survey";
6491
+ if (!usedSlugs.has(cleanBase)) {
6492
+ usedSlugs.add(cleanBase);
6493
+ return cleanBase;
6494
+ }
6495
+ let candidate = `${cleanBase}_copy`;
6496
+ let counter = 2;
6497
+ while (usedSlugs.has(candidate)) {
6498
+ candidate = `${cleanBase}_copy_${counter}`;
6499
+ counter += 1;
6500
+ }
6501
+ usedSlugs.add(candidate);
6502
+ return candidate;
6503
+ }
6185
6504
  const ciSurveyService = ({ strapi }) => ({
6505
+ async deleteResponsesForSurveyRecord(survey) {
6506
+ if (!survey) return 0;
6507
+ const existing = await this.getResponsesForSurvey(survey);
6508
+ const count = existing.length;
6509
+ if (count > 0) {
6510
+ const ids = existing.map((r) => r.id).filter((id) => id !== void 0 && id !== null);
6511
+ if (ids.length > 0) {
6512
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6513
+ where: { id: { $in: ids } }
6514
+ });
6515
+ }
6516
+ }
6517
+ if (survey.slug) {
6518
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6519
+ where: { surveySlug: survey.slug }
6520
+ });
6521
+ }
6522
+ return count;
6523
+ },
6186
6524
  async ensureSeeded(forceReseedResponses = false) {
6187
6525
  if (activeSeedPromise && !forceReseedResponses) {
6188
6526
  return activeSeedPromise;
6189
6527
  }
6190
6528
  const runSeed = async () => {
6529
+ if (!forceReseedResponses && await isDemoSeedBlocked(strapi, "surveys")) {
6530
+ return;
6531
+ }
6191
6532
  let existingSurveys = [];
6192
6533
  try {
6193
6534
  existingSurveys = await strapi.db.query(SURVEY_UID).findMany() || [];
6194
6535
  } catch {
6195
6536
  return;
6196
6537
  }
6538
+ const isFreshEmptyDb = existingSurveys.length === 0;
6197
6539
  const bySlug = {};
6198
6540
  for (const s of existingSurveys) {
6199
6541
  if (s?.slug) bySlug[s.slug] = s;
6200
6542
  }
6201
- for (const seed of DEFAULT_SEED_SURVEYS) {
6202
- if (!bySlug[seed.slug]) {
6203
- const created = await strapi.db.query(SURVEY_UID).create({
6204
- data: seed
6205
- });
6206
- bySlug[seed.slug] = created;
6543
+ if (isFreshEmptyDb || forceReseedResponses) {
6544
+ for (const seed of DEFAULT_SEED_SURVEYS) {
6545
+ if (!bySlug[seed.slug]) {
6546
+ const created = await strapi.db.query(SURVEY_UID).create({
6547
+ data: seed
6548
+ });
6549
+ bySlug[seed.slug] = created;
6550
+ }
6207
6551
  }
6208
6552
  }
6209
6553
  const totalResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
6210
- if (totalResponses === 0 || forceReseedResponses) {
6554
+ if (isFreshEmptyDb && totalResponses === 0 || forceReseedResponses) {
6211
6555
  if (forceReseedResponses) {
6212
6556
  const demoSlugs = DEFAULT_SEED_SURVEYS.map((s) => s.slug);
6213
6557
  for (const slug of demoSlugs) {
6214
- await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6215
- where: { surveySlug: slug }
6216
- });
6558
+ const demoSrv = bySlug[slug];
6559
+ if (demoSrv) {
6560
+ await this.deleteResponsesForSurveyRecord(demoSrv);
6561
+ } else {
6562
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6563
+ where: { surveySlug: slug }
6564
+ });
6565
+ }
6217
6566
  }
6218
6567
  }
6219
6568
  const rows = generateSeedSurveyResponses(bySlug);
@@ -6229,6 +6578,7 @@ const ciSurveyService = ({ strapi }) => ({
6229
6578
  );
6230
6579
  }
6231
6580
  }
6581
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6232
6582
  };
6233
6583
  activeSeedPromise = runSeed().finally(() => {
6234
6584
  activeSeedPromise = null;
@@ -6236,9 +6586,10 @@ const ciSurveyService = ({ strapi }) => ({
6236
6586
  return activeSeedPromise;
6237
6587
  },
6238
6588
  async reseedSampleData() {
6589
+ await setDemoSeedCleared(strapi, false);
6239
6590
  await this.ensureSeeded(true);
6240
6591
  try {
6241
- await strapi.plugin("content-input").service("ci-form").ensureSampleSubmissions(true);
6592
+ await strapi.plugin("content-input").service("ci-form").ensureSeeded(true);
6242
6593
  } catch {
6243
6594
  }
6244
6595
  const totalSurveyResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
@@ -6247,6 +6598,47 @@ const ciSurveyService = ({ strapi }) => ({
6247
6598
  totalSurveyResponses
6248
6599
  };
6249
6600
  },
6601
+ async purgeDemoData() {
6602
+ await setDemoSeedCleared(strapi, true);
6603
+ const demoSlugs = DEFAULT_SEED_SURVEYS.map((s) => s.slug);
6604
+ let deletedSurveys = 0;
6605
+ let deletedSurveyResponses = 0;
6606
+ for (const slug of demoSlugs) {
6607
+ const found = await strapi.db.query(SURVEY_UID).findOne({
6608
+ where: { slug }
6609
+ });
6610
+ if (found) {
6611
+ deletedSurveyResponses += await this.deleteResponsesForSurveyRecord(found);
6612
+ await strapi.db.query(SURVEY_UID).delete({ where: { id: found.id } });
6613
+ deletedSurveys += 1;
6614
+ } else {
6615
+ const orphanRows = await strapi.db.query(SURVEY_RESPONSE_UID).findMany({
6616
+ where: { surveySlug: slug }
6617
+ }) || [];
6618
+ if (orphanRows.length > 0) {
6619
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6620
+ where: { surveySlug: slug }
6621
+ });
6622
+ deletedSurveyResponses += orphanRows.length;
6623
+ }
6624
+ }
6625
+ }
6626
+ let deletedForms = 0;
6627
+ let deletedFormSubmissions = 0;
6628
+ try {
6629
+ const formRes = await strapi.plugin("content-input").service("ci-form").purgeDemoForms();
6630
+ deletedForms = Number(formRes?.deletedForms || 0);
6631
+ deletedFormSubmissions = Number(formRes?.deletedFormSubmissions || 0);
6632
+ } catch {
6633
+ }
6634
+ return {
6635
+ ok: true,
6636
+ deletedSurveys,
6637
+ deletedSurveyResponses,
6638
+ deletedForms,
6639
+ deletedFormSubmissions
6640
+ };
6641
+ },
6250
6642
  async findRawByIdOrSlug(idOrSlug) {
6251
6643
  await this.ensureSeeded(false);
6252
6644
  const raw = String(idOrSlug || "").trim();
@@ -6362,9 +6754,7 @@ const ciSurveyService = ({ strapi }) => ({
6362
6754
  },
6363
6755
  async save(payload) {
6364
6756
  const cleanTitle = String(payload.title || "Yeni Anket").trim();
6365
- const cleanSlug = String(
6366
- payload.slug || slugifyIdentifier(cleanTitle) || `survey_${Date.now()}`
6367
- ).trim();
6757
+ const cleanSlug = slugifyIdentifier(String(payload.slug || "")) || slugifyIdentifier(cleanTitle) || `survey_${Date.now()}`;
6368
6758
  let existing = null;
6369
6759
  if (payload.id) {
6370
6760
  const rawId = String(payload.id).trim();
@@ -6419,17 +6809,36 @@ const ciSurveyService = ({ strapi }) => ({
6419
6809
  const created = await strapi.db.query(SURVEY_UID).create({
6420
6810
  data: recordData
6421
6811
  });
6812
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6422
6813
  return formatSurveyForAdmin(created, { responseCount: 0 });
6423
6814
  },
6424
6815
  async remove(idOrSlug) {
6425
6816
  const found = await this.findRawByIdOrSlug(idOrSlug);
6817
+ let deletedResponses = 0;
6426
6818
  if (found) {
6427
- await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6428
- where: { surveySlug: found.slug }
6429
- });
6819
+ deletedResponses = await this.deleteResponsesForSurveyRecord(found);
6430
6820
  await strapi.db.query(SURVEY_UID).delete({ where: { id: found.id } });
6821
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6431
6822
  }
6432
- return { success: true };
6823
+ return { success: true, deletedResponses };
6824
+ },
6825
+ async clearResponses(idOrSlug) {
6826
+ const found = await this.findRawByIdOrSlug(idOrSlug);
6827
+ if (!found) {
6828
+ return null;
6829
+ }
6830
+ const deletedCount = await this.deleteResponsesForSurveyRecord(found);
6831
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6832
+ return {
6833
+ ok: true,
6834
+ slug: found.slug,
6835
+ deletedCount,
6836
+ survey: formatSurveyForAdmin(found, {
6837
+ responseCount: 0,
6838
+ npsScore: null,
6839
+ lastSubmittedAt: null
6840
+ })
6841
+ };
6433
6842
  },
6434
6843
  async submitSurvey(idOrSlug, rawBody, meta = {}) {
6435
6844
  const survey = await this.findRawByIdOrSlug(idOrSlug);
@@ -6709,6 +7118,188 @@ const ciSurveyService = ({ strapi }) => ({
6709
7118
  contentType: "text/csv; charset=utf-8",
6710
7119
  body: csv
6711
7120
  };
7121
+ },
7122
+ async exportBundle(targetIdOrAll = "all", mode = "structure") {
7123
+ await this.ensureSeeded(false);
7124
+ const cleanTarget = String(targetIdOrAll || "all").trim();
7125
+ const exportMode = mode === "full" ? "full" : "structure";
7126
+ let targetSurveys = [];
7127
+ if (!cleanTarget || cleanTarget === "all") {
7128
+ targetSurveys = await strapi.db.query(SURVEY_UID).findMany({
7129
+ orderBy: { id: "asc" }
7130
+ }) || [];
7131
+ } else {
7132
+ const single = await this.findRawByIdOrSlug(cleanTarget);
7133
+ if (!single) {
7134
+ return null;
7135
+ }
7136
+ targetSurveys = [single];
7137
+ }
7138
+ const portableSurveys = [];
7139
+ let totalResponses = 0;
7140
+ for (const srv of targetSurveys) {
7141
+ const rawResps = exportMode === "full" ? await this.getResponsesForSurvey(srv) : [];
7142
+ const item = sanitizeSurveyForBundle(srv, rawResps);
7143
+ totalResponses += item.responses.length;
7144
+ portableSurveys.push(item);
7145
+ }
7146
+ const dateStamp = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
7147
+ const modeSuffix = exportMode === "full" ? "full-backup" : "structure";
7148
+ const filename = cleanTarget && cleanTarget !== "all" && portableSurveys[0]?.slug ? `${portableSurveys[0].slug}-${modeSuffix}.ci-survey.json` : `ci-surveys-all-${modeSuffix}-${dateStamp}.ci-survey.json`;
7149
+ const bundle = {
7150
+ packageType: "strapi-content-input-survey-bundle",
7151
+ schemaVersion: 1,
7152
+ mode: exportMode,
7153
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
7154
+ surveyCount: portableSurveys.length,
7155
+ totalResponses,
7156
+ surveys: portableSurveys
7157
+ };
7158
+ return {
7159
+ filename,
7160
+ contentType: "application/json; charset=utf-8",
7161
+ bundle
7162
+ };
7163
+ },
7164
+ async importBundle(rawPayload, options2 = {}) {
7165
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
7166
+ let parsed = rawPayload;
7167
+ if (typeof parsed === "string") {
7168
+ try {
7169
+ parsed = JSON.parse(parsed);
7170
+ } catch {
7171
+ const err = new Error("Invalid JSON bundle payload");
7172
+ err.status = 400;
7173
+ throw err;
7174
+ }
7175
+ }
7176
+ let rawItems = [];
7177
+ if (Array.isArray(parsed)) {
7178
+ rawItems = parsed;
7179
+ } else if (parsed && typeof parsed === "object") {
7180
+ if (Array.isArray(parsed.surveys)) {
7181
+ rawItems = parsed.surveys;
7182
+ } else if (Array.isArray(parsed.questions) || parsed.title || parsed.slug) {
7183
+ rawItems = [parsed];
7184
+ }
7185
+ }
7186
+ const validItems = rawItems.filter(
7187
+ (it) => it && typeof it === "object" && (Array.isArray(it.questions) || it.title)
7188
+ );
7189
+ if (validItems.length === 0) {
7190
+ const err = new Error(
7191
+ "No valid survey definitions found in the provided JSON package."
7192
+ );
7193
+ err.status = 400;
7194
+ throw err;
7195
+ }
7196
+ const conflictStrategy = options2.conflictStrategy === "overwrite" ? "overwrite" : "duplicate";
7197
+ const includeResponses = options2.includeResponses !== false;
7198
+ const existingSurveys = await strapi.db.query(SURVEY_UID).findMany() || [];
7199
+ const usedSlugs = new Set(
7200
+ existingSurveys.map((s) => String(s?.slug || "").trim()).filter(Boolean)
7201
+ );
7202
+ const importedSurveys = [];
7203
+ let importedResponsesCount = 0;
7204
+ for (const item of validItems) {
7205
+ const cleanTitle = String(item.title || "Imported Survey").trim();
7206
+ const baseSlug = slugifyIdentifier(String(item.slug || cleanTitle)) || "imported_survey";
7207
+ const existing = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: baseSlug } });
7208
+ const isOverwriting = Boolean(existing && conflictStrategy === "overwrite");
7209
+ const isDuplicatingCollision = Boolean(
7210
+ existing && conflictStrategy === "duplicate"
7211
+ );
7212
+ const finalSlug = isOverwriting ? baseSlug : makeUniqueSlug(baseSlug, usedSlugs);
7213
+ const finalTitle = isDuplicatingCollision ? `${cleanTitle} (Copy)` : cleanTitle;
7214
+ const rawTitleI18n = item.titleI18n && typeof item.titleI18n === "object" ? { ...item.titleI18n } : { tr: cleanTitle, en: cleanTitle };
7215
+ if (isDuplicatingCollision) {
7216
+ for (const k of Object.keys(rawTitleI18n)) {
7217
+ if (rawTitleI18n[k]) {
7218
+ rawTitleI18n[k] = `${rawTitleI18n[k]} (${k === "tr" ? "Kopya" : "Copy"})`;
7219
+ }
7220
+ }
7221
+ }
7222
+ const savePayload = {
7223
+ ...isOverwriting ? { id: existing.documentId || existing.id } : {},
7224
+ title: finalTitle,
7225
+ titleI18n: rawTitleI18n,
7226
+ slug: finalSlug,
7227
+ description: item.description ?? { tr: "", en: "" },
7228
+ status: item.status || "published",
7229
+ displayMode: item.displayMode || "single_page",
7230
+ startsAt: item.startsAt || null,
7231
+ endsAt: item.endsAt || null,
7232
+ quotaLimit: item.quotaLimit ? Number(item.quotaLimit) : null,
7233
+ submissionPolicy: item.submissionPolicy || "one_per_voter",
7234
+ anonymizeIp: item.anonymizeIp !== void 0 ? Boolean(item.anonymizeIp) : true,
7235
+ showPublicResults: item.showPublicResults || "after_vote",
7236
+ allowBackNavigation: item.allowBackNavigation !== void 0 ? Boolean(item.allowBackNavigation) : true,
7237
+ showProgressBar: item.showProgressBar !== void 0 ? Boolean(item.showProgressBar) : true,
7238
+ useRecaptcha: item.useRecaptcha !== void 0 ? Boolean(item.useRecaptcha) : false,
7239
+ recaptchaSiteKey: item.recaptchaSiteKey ? String(item.recaptchaSiteKey) : "",
7240
+ steps: Array.isArray(item.steps) ? item.steps : [],
7241
+ questions: Array.isArray(item.questions) ? item.questions : [],
7242
+ settings: item.settings && typeof item.settings === "object" ? item.settings : {}
7243
+ };
7244
+ await this.save(savePayload);
7245
+ const savedRaw = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: finalSlug } });
7246
+ if (!savedRaw) continue;
7247
+ const rawResponses = Array.isArray(item.responses) ? item.responses : [];
7248
+ if (includeResponses) {
7249
+ if (isOverwriting) {
7250
+ await this.deleteResponsesForSurveyRecord(savedRaw);
7251
+ }
7252
+ if (rawResponses.length > 0) {
7253
+ const surveyDocOrId = String(savedRaw.documentId || savedRaw.id);
7254
+ const batchSize = 50;
7255
+ for (let i = 0; i < rawResponses.length; i += batchSize) {
7256
+ const chunk = rawResponses.slice(i, i + batchSize);
7257
+ await Promise.all(
7258
+ chunk.map((r) => {
7259
+ const answers = r?.answers && typeof r.answers === "object" && !Array.isArray(r.answers) ? r.answers : {};
7260
+ const otherTexts = r?.otherTexts && typeof r.otherTexts === "object" && !Array.isArray(r.otherTexts) ? r.otherTexts : {};
7261
+ const metrics = computeResponseMetrics(
7262
+ savedRaw,
7263
+ answers
7264
+ );
7265
+ const durationSeconds = typeof r?.durationSeconds === "number" ? Math.max(0, Math.round(r.durationSeconds)) : typeof r?.durationMs === "number" ? Math.max(0, Math.round(r.durationMs / 1e3)) : 0;
7266
+ return strapi.db.query(SURVEY_RESPONSE_UID).create({
7267
+ data: {
7268
+ surveyId: surveyDocOrId,
7269
+ surveySlug: savedRaw.slug,
7270
+ surveyTitle: savedRaw.title,
7271
+ surveyVersion: Number(savedRaw.version || 1),
7272
+ answers,
7273
+ otherTexts,
7274
+ score: typeof r?.score === "number" ? r.score : metrics.score,
7275
+ npsValue: typeof r?.npsValue === "number" ? r.npsValue : metrics.npsValue,
7276
+ npsCategory: r?.npsCategory || metrics.npsCategory,
7277
+ locale: String(r?.locale || "en"),
7278
+ durationSeconds,
7279
+ voterHash: r?.voterHash || null,
7280
+ respondentToken: r?.respondentToken || null,
7281
+ ip: null,
7282
+ userAgent: String(r?.userAgent || "imported"),
7283
+ submittedAt: r?.submittedAt || r?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
7284
+ }
7285
+ });
7286
+ })
7287
+ );
7288
+ }
7289
+ importedResponsesCount += rawResponses.length;
7290
+ }
7291
+ }
7292
+ const finalAdminObj = await this.findOneAdmin(finalSlug);
7293
+ if (finalAdminObj) {
7294
+ importedSurveys.push(finalAdminObj);
7295
+ }
7296
+ }
7297
+ return {
7298
+ ok: true,
7299
+ importedCount: importedSurveys.length,
7300
+ importedResponsesCount,
7301
+ importedSurveys
7302
+ };
6712
7303
  }
6713
7304
  });
6714
7305
  const PALETTE_UID = "plugin::content-input.ci-color-palette";