@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.
@@ -1945,6 +1945,79 @@ const ciSurveyController = ({ strapi }) => ({
1945
1945
  } catch (err) {
1946
1946
  ctx.throw(500, err);
1947
1947
  }
1948
+ },
1949
+ async purgeDemo(ctx) {
1950
+ try {
1951
+ const res = await strapi.plugin("content-input").service("ci-survey").purgeDemoData();
1952
+ ctx.status = 200;
1953
+ ctx.body = res;
1954
+ } catch (err) {
1955
+ ctx.throw(500, err);
1956
+ }
1957
+ },
1958
+ async clearResponses(ctx) {
1959
+ try {
1960
+ const { id } = ctx.params;
1961
+ const res = await strapi.plugin("content-input").service("ci-survey").clearResponses(id);
1962
+ if (!res) {
1963
+ return ctx.notFound("Survey not found");
1964
+ }
1965
+ ctx.status = 200;
1966
+ ctx.body = res;
1967
+ } catch (err) {
1968
+ ctx.throw(500, err);
1969
+ }
1970
+ },
1971
+ async exportBundle(ctx) {
1972
+ try {
1973
+ const target = String(ctx.query?.target || "all").trim();
1974
+ const rawMode = String(ctx.query?.mode || "structure").trim().toLowerCase();
1975
+ const mode = rawMode === "full" ? "full" : "structure";
1976
+ const directDownload = String(ctx.query?.download || "") === "1";
1977
+ const exported = await strapi.plugin("content-input").service("ci-survey").exportBundle(target, mode);
1978
+ if (!exported) {
1979
+ return ctx.notFound("Survey not found");
1980
+ }
1981
+ if (directDownload) {
1982
+ ctx.body = JSON.stringify(exported.bundle, null, 2);
1983
+ ctx.type = exported.contentType;
1984
+ ctx.set("Content-Type", exported.contentType);
1985
+ ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
1986
+ ctx.status = 200;
1987
+ return;
1988
+ }
1989
+ ctx.status = 200;
1990
+ ctx.body = {
1991
+ filename: exported.filename,
1992
+ bundle: exported.bundle
1993
+ };
1994
+ } catch (err) {
1995
+ ctx.throw(500, err);
1996
+ }
1997
+ },
1998
+ async importBundle(ctx) {
1999
+ try {
2000
+ const rawBody = ctx.request.body || {};
2001
+ const hasEnvelope = rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) && rawBody.bundle !== void 0;
2002
+ const bundlePayload = hasEnvelope ? rawBody.bundle : rawBody;
2003
+ const rawStrategy = String(
2004
+ (hasEnvelope ? rawBody.conflictStrategy : ctx.query?.conflictStrategy) || "duplicate"
2005
+ ).trim().toLowerCase();
2006
+ const conflictStrategy = rawStrategy === "overwrite" ? "overwrite" : "duplicate";
2007
+ const rawInclude = hasEnvelope ? rawBody.includeResponses : ctx.query?.includeResponses;
2008
+ const includeResponses = rawInclude === void 0 ? true : rawInclude !== false && String(rawInclude).toLowerCase() !== "false";
2009
+ const res = await strapi.plugin("content-input").service("ci-survey").importBundle(bundlePayload, {
2010
+ conflictStrategy,
2011
+ includeResponses
2012
+ });
2013
+ ctx.status = 200;
2014
+ ctx.body = res;
2015
+ } catch (err) {
2016
+ if (err?.status === 400) {
2017
+ return ctx.badRequest(err.message || "Invalid survey bundle");
2018
+ }
2019
+ ctx.throw(500, err);
2020
+ }
1948
2021
  }
1949
2022
  });
1950
2023
  const ciColorController = ({ strapi }) => ({
@@ -2258,6 +2331,46 @@ const routes = {
2258
2331
  policies: []
2259
2332
  }
2260
2333
  },
2334
+ {
2335
+ method: "POST",
2336
+ path: "/surveys/purge-demo",
2337
+ handler: "ci-survey.purgeDemo",
2338
+ config: {
2339
+ policies: []
2340
+ }
2341
+ },
2342
+ {
2343
+ method: "GET",
2344
+ path: "/survey-bundle/export",
2345
+ handler: "ci-survey.exportBundle",
2346
+ config: {
2347
+ policies: []
2348
+ }
2349
+ },
2350
+ {
2351
+ method: "POST",
2352
+ path: "/survey-bundle/import",
2353
+ handler: "ci-survey.importBundle",
2354
+ config: {
2355
+ policies: []
2356
+ }
2357
+ },
2358
+ {
2359
+ method: "GET",
2360
+ path: "/surveys/bundle/export",
2361
+ handler: "ci-survey.exportBundle",
2362
+ config: {
2363
+ policies: []
2364
+ }
2365
+ },
2366
+ {
2367
+ method: "POST",
2368
+ path: "/surveys/bundle/import",
2369
+ handler: "ci-survey.importBundle",
2370
+ config: {
2371
+ policies: []
2372
+ }
2373
+ },
2261
2374
  {
2262
2375
  method: "POST",
2263
2376
  path: "/surveys",
@@ -2282,6 +2395,14 @@ const routes = {
2282
2395
  policies: []
2283
2396
  }
2284
2397
  },
2398
+ {
2399
+ method: "DELETE",
2400
+ path: "/surveys/:id/responses",
2401
+ handler: "ci-survey.clearResponses",
2402
+ config: {
2403
+ policies: []
2404
+ }
2405
+ },
2285
2406
  {
2286
2407
  method: "GET",
2287
2408
  path: "/surveys/:id/analytics",
@@ -4503,6 +4624,84 @@ function generateSampleFormSubmissions(formEntry) {
4503
4624
  }
4504
4625
  return list;
4505
4626
  }
4627
+ const DEMO_SEED_STORE_KEY = "demo_seed_state";
4628
+ const fallbackStore = /* @__PURE__ */ new WeakMap();
4629
+ function isDemoSeedDisabledByEnv() {
4630
+ const raw = String(process.env.CI_DISABLE_DEMO_SEED || "").trim().toLowerCase();
4631
+ return raw === "true" || raw === "1" || raw === "yes";
4632
+ }
4633
+ function getPluginStore(strapi) {
4634
+ if (strapi && typeof strapi.store === "function") {
4635
+ return strapi.store({
4636
+ type: "plugin",
4637
+ name: "content-input"
4638
+ });
4639
+ }
4640
+ return null;
4641
+ }
4642
+ async function getDemoSeedState(strapi) {
4643
+ const disabledByEnv = isDemoSeedDisabledByEnv();
4644
+ let stored = null;
4645
+ try {
4646
+ const store = getPluginStore(strapi);
4647
+ if (store && typeof store.get === "function") {
4648
+ const val = await store.get({ key: DEMO_SEED_STORE_KEY });
4649
+ if (val && typeof val === "object") {
4650
+ stored = val;
4651
+ }
4652
+ } else if (strapi && typeof strapi === "object") {
4653
+ stored = fallbackStore.get(strapi) || null;
4654
+ }
4655
+ } catch {
4656
+ if (strapi && typeof strapi === "object") {
4657
+ stored = fallbackStore.get(strapi) || null;
4658
+ }
4659
+ }
4660
+ return {
4661
+ cleared: Boolean(stored?.cleared),
4662
+ surveysInitialized: Boolean(stored?.surveysInitialized),
4663
+ formsInitialized: Boolean(stored?.formsInitialized),
4664
+ updatedAt: stored?.updatedAt || "",
4665
+ disabledByEnv
4666
+ };
4667
+ }
4668
+ async function updateDemoSeedState(strapi, patch) {
4669
+ const current = await getDemoSeedState(strapi);
4670
+ const next = {
4671
+ cleared: patch.cleared !== void 0 ? Boolean(patch.cleared) : current.cleared,
4672
+ surveysInitialized: patch.surveysInitialized !== void 0 ? Boolean(patch.surveysInitialized) : Boolean(current.surveysInitialized),
4673
+ formsInitialized: patch.formsInitialized !== void 0 ? Boolean(patch.formsInitialized) : Boolean(current.formsInitialized),
4674
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4675
+ };
4676
+ if (strapi && typeof strapi === "object") {
4677
+ fallbackStore.set(strapi, next);
4678
+ }
4679
+ try {
4680
+ const store = getPluginStore(strapi);
4681
+ if (store && typeof store.set === "function") {
4682
+ await store.set({
4683
+ key: DEMO_SEED_STORE_KEY,
4684
+ value: next
4685
+ });
4686
+ }
4687
+ } catch {
4688
+ }
4689
+ return next;
4690
+ }
4691
+ async function isDemoSeedBlocked(strapi, domain) {
4692
+ const state = await getDemoSeedState(strapi);
4693
+ if (state.disabledByEnv || state.cleared) return true;
4694
+ if (domain === "surveys" && state.surveysInitialized) return true;
4695
+ if (domain === "forms" && state.formsInitialized) return true;
4696
+ return false;
4697
+ }
4698
+ async function setDemoSeedCleared(strapi, cleared) {
4699
+ return updateDemoSeedState(strapi, {
4700
+ cleared,
4701
+ surveysInitialized: true,
4702
+ formsInitialized: true
4703
+ });
4704
+ }
4506
4705
  const FORM_UID = "plugin::content-input.ci-form";
4507
4706
  const SUBMISSION_UID = "plugin::content-input.ci-form-submission";
4508
4707
  function slugifyIdentifier$1(text) {
@@ -4520,7 +4719,7 @@ function slugifyIdentifier$1(text) {
4520
4719
  ü: "u",
4521
4720
  Ü: "u"
4522
4721
  };
4523
- return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
4722
+ return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-{2,}/g, "-").replace(/_{2,}/g, "_").replace(/^[-_]+|[-_]+$/g, "");
4524
4723
  }
4525
4724
  function stripHtmlTags(html) {
4526
4725
  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();
@@ -4831,11 +5030,20 @@ const ciFormService = ({ strapi }) => ({
4831
5030
  },
4832
5031
  async ensureSampleSubmissions(force = false) {
4833
5032
  try {
5033
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5034
+ return;
5035
+ }
4834
5036
  const subCount = await strapi.db.query(SUBMISSION_UID).count();
4835
5037
  if (subCount > 0 && !force) return;
4836
- const showcaseForm = await strapi.db.query(FORM_UID).findOne({
5038
+ let showcaseForm = await strapi.db.query(FORM_UID).findOne({
4837
5039
  where: { slug: "showcase_contact_form" }
4838
5040
  });
5041
+ if (!showcaseForm && force) {
5042
+ const seedDef = DEFAULT_SEED_FORMS.find((s) => s.slug === "showcase_contact_form");
5043
+ if (seedDef) {
5044
+ showcaseForm = await strapi.db.query(FORM_UID).create({ data: seedDef });
5045
+ }
5046
+ }
4839
5047
  if (!showcaseForm) return;
4840
5048
  if (force) {
4841
5049
  await strapi.db.query(SUBMISSION_UID).deleteMany({
@@ -4849,16 +5057,24 @@ const ciFormService = ({ strapi }) => ({
4849
5057
  } catch {
4850
5058
  }
4851
5059
  },
4852
- async ensureSeeded() {
5060
+ async ensureSeeded(force = false) {
5061
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5062
+ return;
5063
+ }
4853
5064
  let count = 0;
4854
5065
  try {
4855
5066
  count = await strapi.db.query(FORM_UID).count();
4856
5067
  } catch {
4857
5068
  return;
4858
5069
  }
4859
- if (count === 0) {
5070
+ if (count === 0 || force) {
4860
5071
  for (const seed of DEFAULT_SEED_FORMS) {
4861
- await strapi.db.query(FORM_UID).create({ data: seed });
5072
+ const existingSeed = await strapi.db.query(FORM_UID).findOne({
5073
+ where: { slug: seed.slug }
5074
+ });
5075
+ if (!existingSeed) {
5076
+ await strapi.db.query(FORM_UID).create({ data: seed });
5077
+ }
4862
5078
  }
4863
5079
  } else {
4864
5080
  try {
@@ -4877,7 +5093,52 @@ const ciFormService = ({ strapi }) => ({
4877
5093
  } catch {
4878
5094
  }
4879
5095
  }
4880
- await this.ensureSampleSubmissions(false);
5096
+ await this.ensureSampleSubmissions(force);
5097
+ await updateDemoSeedState(strapi, { formsInitialized: true });
5098
+ },
5099
+ async purgeDemoForms() {
5100
+ let deletedForms = 0;
5101
+ let deletedFormSubmissions = 0;
5102
+ const demoSlugs = DEFAULT_SEED_FORMS.map((f) => f.slug);
5103
+ for (const slug of demoSlugs) {
5104
+ try {
5105
+ const existingForm = await strapi.db.query(FORM_UID).findOne({
5106
+ where: { slug }
5107
+ });
5108
+ const matchingSubs = await strapi.db.query(SUBMISSION_UID).findMany({
5109
+ where: existingForm ? {
5110
+ $or: [
5111
+ { formSlug: slug },
5112
+ { formId: String(existingForm.documentId || existingForm.id) },
5113
+ { formId: String(existingForm.id) }
5114
+ ]
5115
+ } : { formSlug: slug }
5116
+ }) || [];
5117
+ if (matchingSubs.length > 0) {
5118
+ const subIds = matchingSubs.map((s) => s.id).filter((id) => id !== void 0 && id !== null);
5119
+ if (subIds.length > 0) {
5120
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
5121
+ where: { id: { $in: subIds } }
5122
+ });
5123
+ }
5124
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
5125
+ where: { formSlug: slug }
5126
+ });
5127
+ deletedFormSubmissions += matchingSubs.length;
5128
+ }
5129
+ if (existingForm) {
5130
+ await strapi.db.query(FORM_UID).delete({
5131
+ where: { id: existingForm.id }
5132
+ });
5133
+ deletedForms += 1;
5134
+ }
5135
+ } catch {
5136
+ }
5137
+ }
5138
+ return {
5139
+ deletedForms,
5140
+ deletedFormSubmissions
5141
+ };
4881
5142
  },
4882
5143
  async findRawByIdOrSlug(idOrSlug) {
4883
5144
  await this.ensureSeeded();
@@ -6090,7 +6351,7 @@ function slugifyIdentifier(text) {
6090
6351
  ü: "u",
6091
6352
  Ü: "u"
6092
6353
  };
6093
- return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
6354
+ return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-{2,}/g, "-").replace(/_{2,}/g, "_").replace(/^[-_]+|[-_]+$/g, "");
6094
6355
  }
6095
6356
  function getEnvRecaptchaPublicKey() {
6096
6357
  return (process.env.MIX_RECAPTCHA_PUBLIC_KEY || process.env.RECAPTCHA_PUBLIC_KEY || process.env.NUXT_PUBLIC_RECAPTCHA_SITE_KEY || "").trim();
@@ -6157,38 +6418,126 @@ function sanitizeSurveyForPublic(entry, extra = {}) {
6157
6418
  publicResults: extra.publicResults || null
6158
6419
  };
6159
6420
  }
6421
+ function sanitizeSurveyForBundle(entry, rawResponses) {
6422
+ const cleanTitle = String(entry?.title || "Untitled Survey").trim();
6423
+ const cleanSlug = String(entry?.slug || slugifyIdentifier(cleanTitle) || "survey").trim();
6424
+ const sortedResponses = Array.isArray(rawResponses) ? [...rawResponses].sort((a, b) => {
6425
+ const ta = new Date(a?.submittedAt || a?.createdAt || 0).getTime();
6426
+ const tb = new Date(b?.submittedAt || b?.createdAt || 0).getTime();
6427
+ return ta - tb;
6428
+ }) : [];
6429
+ return {
6430
+ title: cleanTitle,
6431
+ titleI18n: entry?.titleI18n || { tr: cleanTitle, en: cleanTitle },
6432
+ slug: cleanSlug,
6433
+ description: entry?.description ?? { tr: "", en: "" },
6434
+ status: entry?.status || "published",
6435
+ displayMode: entry?.displayMode || "single_page",
6436
+ startsAt: entry?.startsAt || null,
6437
+ endsAt: entry?.endsAt || null,
6438
+ quotaLimit: entry?.quotaLimit ? Number(entry.quotaLimit) : null,
6439
+ submissionPolicy: entry?.submissionPolicy || "one_per_voter",
6440
+ anonymizeIp: entry?.anonymizeIp !== void 0 ? Boolean(entry.anonymizeIp) : true,
6441
+ showPublicResults: entry?.showPublicResults || "after_vote",
6442
+ allowBackNavigation: entry?.allowBackNavigation !== void 0 ? Boolean(entry.allowBackNavigation) : true,
6443
+ showProgressBar: entry?.showProgressBar !== void 0 ? Boolean(entry.showProgressBar) : true,
6444
+ useRecaptcha: entry?.useRecaptcha !== void 0 ? Boolean(entry.useRecaptcha) : false,
6445
+ recaptchaSiteKey: entry?.recaptchaSiteKey ? String(entry.recaptchaSiteKey) : "",
6446
+ steps: Array.isArray(entry?.steps) ? entry.steps : [],
6447
+ questions: Array.isArray(entry?.questions) ? entry.questions : [],
6448
+ settings: entry?.settings && typeof entry.settings === "object" ? entry.settings : {},
6449
+ version: Number(entry?.version || 1),
6450
+ responses: sortedResponses.map((r) => ({
6451
+ answers: r?.answers && typeof r.answers === "object" && !Array.isArray(r.answers) ? r.answers : {},
6452
+ otherTexts: r?.otherTexts && typeof r.otherTexts === "object" && !Array.isArray(r.otherTexts) ? r.otherTexts : {},
6453
+ score: typeof r?.score === "number" ? r.score : null,
6454
+ npsValue: typeof r?.npsValue === "number" ? r.npsValue : null,
6455
+ npsCategory: r?.npsCategory || null,
6456
+ locale: String(r?.locale || "en"),
6457
+ durationSeconds: Math.max(0, Number(r?.durationSeconds || 0) || 0),
6458
+ voterHash: r?.voterHash || null,
6459
+ respondentToken: r?.respondentToken || null,
6460
+ submittedAt: r?.submittedAt || r?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
6461
+ }))
6462
+ };
6463
+ }
6464
+ function makeUniqueSlug(baseSlug, usedSlugs) {
6465
+ const cleanBase = slugifyIdentifier(baseSlug) || "survey";
6466
+ if (!usedSlugs.has(cleanBase)) {
6467
+ usedSlugs.add(cleanBase);
6468
+ return cleanBase;
6469
+ }
6470
+ let candidate = `${cleanBase}_copy`;
6471
+ let counter = 2;
6472
+ while (usedSlugs.has(candidate)) {
6473
+ candidate = `${cleanBase}_copy_${counter}`;
6474
+ counter += 1;
6475
+ }
6476
+ usedSlugs.add(candidate);
6477
+ return candidate;
6478
+ }
6160
6479
  const ciSurveyService = ({ strapi }) => ({
6480
+ async deleteResponsesForSurveyRecord(survey) {
6481
+ if (!survey) return 0;
6482
+ const existing = await this.getResponsesForSurvey(survey);
6483
+ const count = existing.length;
6484
+ if (count > 0) {
6485
+ const ids = existing.map((r) => r.id).filter((id) => id !== void 0 && id !== null);
6486
+ if (ids.length > 0) {
6487
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6488
+ where: { id: { $in: ids } }
6489
+ });
6490
+ }
6491
+ }
6492
+ if (survey.slug) {
6493
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6494
+ where: { surveySlug: survey.slug }
6495
+ });
6496
+ }
6497
+ return count;
6498
+ },
6161
6499
  async ensureSeeded(forceReseedResponses = false) {
6162
6500
  if (activeSeedPromise && !forceReseedResponses) {
6163
6501
  return activeSeedPromise;
6164
6502
  }
6165
6503
  const runSeed = async () => {
6504
+ if (!forceReseedResponses && await isDemoSeedBlocked(strapi, "surveys")) {
6505
+ return;
6506
+ }
6166
6507
  let existingSurveys = [];
6167
6508
  try {
6168
6509
  existingSurveys = await strapi.db.query(SURVEY_UID).findMany() || [];
6169
6510
  } catch {
6170
6511
  return;
6171
6512
  }
6513
+ const isFreshEmptyDb = existingSurveys.length === 0;
6172
6514
  const bySlug = {};
6173
6515
  for (const s of existingSurveys) {
6174
6516
  if (s?.slug) bySlug[s.slug] = s;
6175
6517
  }
6176
- for (const seed of DEFAULT_SEED_SURVEYS) {
6177
- if (!bySlug[seed.slug]) {
6178
- const created = await strapi.db.query(SURVEY_UID).create({
6179
- data: seed
6180
- });
6181
- bySlug[seed.slug] = created;
6518
+ if (isFreshEmptyDb || forceReseedResponses) {
6519
+ for (const seed of DEFAULT_SEED_SURVEYS) {
6520
+ if (!bySlug[seed.slug]) {
6521
+ const created = await strapi.db.query(SURVEY_UID).create({
6522
+ data: seed
6523
+ });
6524
+ bySlug[seed.slug] = created;
6525
+ }
6182
6526
  }
6183
6527
  }
6184
6528
  const totalResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
6185
- if (totalResponses === 0 || forceReseedResponses) {
6529
+ if (isFreshEmptyDb && totalResponses === 0 || forceReseedResponses) {
6186
6530
  if (forceReseedResponses) {
6187
6531
  const demoSlugs = DEFAULT_SEED_SURVEYS.map((s) => s.slug);
6188
6532
  for (const slug of demoSlugs) {
6189
- await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6190
- where: { surveySlug: slug }
6191
- });
6533
+ const demoSrv = bySlug[slug];
6534
+ if (demoSrv) {
6535
+ await this.deleteResponsesForSurveyRecord(demoSrv);
6536
+ } else {
6537
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6538
+ where: { surveySlug: slug }
6539
+ });
6540
+ }
6192
6541
  }
6193
6542
  }
6194
6543
  const rows = generateSeedSurveyResponses(bySlug);
@@ -6204,6 +6553,7 @@ const ciSurveyService = ({ strapi }) => ({
6204
6553
  );
6205
6554
  }
6206
6555
  }
6556
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6207
6557
  };
6208
6558
  activeSeedPromise = runSeed().finally(() => {
6209
6559
  activeSeedPromise = null;
@@ -6211,9 +6561,10 @@ const ciSurveyService = ({ strapi }) => ({
6211
6561
  return activeSeedPromise;
6212
6562
  },
6213
6563
  async reseedSampleData() {
6564
+ await setDemoSeedCleared(strapi, false);
6214
6565
  await this.ensureSeeded(true);
6215
6566
  try {
6216
- await strapi.plugin("content-input").service("ci-form").ensureSampleSubmissions(true);
6567
+ await strapi.plugin("content-input").service("ci-form").ensureSeeded(true);
6217
6568
  } catch {
6218
6569
  }
6219
6570
  const totalSurveyResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
@@ -6222,6 +6573,47 @@ const ciSurveyService = ({ strapi }) => ({
6222
6573
  totalSurveyResponses
6223
6574
  };
6224
6575
  },
6576
+ async purgeDemoData() {
6577
+ await setDemoSeedCleared(strapi, true);
6578
+ const demoSlugs = DEFAULT_SEED_SURVEYS.map((s) => s.slug);
6579
+ let deletedSurveys = 0;
6580
+ let deletedSurveyResponses = 0;
6581
+ for (const slug of demoSlugs) {
6582
+ const found = await strapi.db.query(SURVEY_UID).findOne({
6583
+ where: { slug }
6584
+ });
6585
+ if (found) {
6586
+ deletedSurveyResponses += await this.deleteResponsesForSurveyRecord(found);
6587
+ await strapi.db.query(SURVEY_UID).delete({ where: { id: found.id } });
6588
+ deletedSurveys += 1;
6589
+ } else {
6590
+ const orphanRows = await strapi.db.query(SURVEY_RESPONSE_UID).findMany({
6591
+ where: { surveySlug: slug }
6592
+ }) || [];
6593
+ if (orphanRows.length > 0) {
6594
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6595
+ where: { surveySlug: slug }
6596
+ });
6597
+ deletedSurveyResponses += orphanRows.length;
6598
+ }
6599
+ }
6600
+ }
6601
+ let deletedForms = 0;
6602
+ let deletedFormSubmissions = 0;
6603
+ try {
6604
+ const formRes = await strapi.plugin("content-input").service("ci-form").purgeDemoForms();
6605
+ deletedForms = Number(formRes?.deletedForms || 0);
6606
+ deletedFormSubmissions = Number(formRes?.deletedFormSubmissions || 0);
6607
+ } catch {
6608
+ }
6609
+ return {
6610
+ ok: true,
6611
+ deletedSurveys,
6612
+ deletedSurveyResponses,
6613
+ deletedForms,
6614
+ deletedFormSubmissions
6615
+ };
6616
+ },
6225
6617
  async findRawByIdOrSlug(idOrSlug) {
6226
6618
  await this.ensureSeeded(false);
6227
6619
  const raw = String(idOrSlug || "").trim();
@@ -6337,9 +6729,7 @@ const ciSurveyService = ({ strapi }) => ({
6337
6729
  },
6338
6730
  async save(payload) {
6339
6731
  const cleanTitle = String(payload.title || "Yeni Anket").trim();
6340
- const cleanSlug = String(
6341
- payload.slug || slugifyIdentifier(cleanTitle) || `survey_${Date.now()}`
6342
- ).trim();
6732
+ const cleanSlug = slugifyIdentifier(String(payload.slug || "")) || slugifyIdentifier(cleanTitle) || `survey_${Date.now()}`;
6343
6733
  let existing = null;
6344
6734
  if (payload.id) {
6345
6735
  const rawId = String(payload.id).trim();
@@ -6394,17 +6784,36 @@ const ciSurveyService = ({ strapi }) => ({
6394
6784
  const created = await strapi.db.query(SURVEY_UID).create({
6395
6785
  data: recordData
6396
6786
  });
6787
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6397
6788
  return formatSurveyForAdmin(created, { responseCount: 0 });
6398
6789
  },
6399
6790
  async remove(idOrSlug) {
6400
6791
  const found = await this.findRawByIdOrSlug(idOrSlug);
6792
+ let deletedResponses = 0;
6401
6793
  if (found) {
6402
- await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6403
- where: { surveySlug: found.slug }
6404
- });
6794
+ deletedResponses = await this.deleteResponsesForSurveyRecord(found);
6405
6795
  await strapi.db.query(SURVEY_UID).delete({ where: { id: found.id } });
6796
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6406
6797
  }
6407
- return { success: true };
6798
+ return { success: true, deletedResponses };
6799
+ },
6800
+ async clearResponses(idOrSlug) {
6801
+ const found = await this.findRawByIdOrSlug(idOrSlug);
6802
+ if (!found) {
6803
+ return null;
6804
+ }
6805
+ const deletedCount = await this.deleteResponsesForSurveyRecord(found);
6806
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6807
+ return {
6808
+ ok: true,
6809
+ slug: found.slug,
6810
+ deletedCount,
6811
+ survey: formatSurveyForAdmin(found, {
6812
+ responseCount: 0,
6813
+ npsScore: null,
6814
+ lastSubmittedAt: null
6815
+ })
6816
+ };
6408
6817
  },
6409
6818
  async submitSurvey(idOrSlug, rawBody, meta = {}) {
6410
6819
  const survey = await this.findRawByIdOrSlug(idOrSlug);
@@ -6684,6 +7093,188 @@ const ciSurveyService = ({ strapi }) => ({
6684
7093
  contentType: "text/csv; charset=utf-8",
6685
7094
  body: csv
6686
7095
  };
7096
+ },
7097
+ async exportBundle(targetIdOrAll = "all", mode = "structure") {
7098
+ await this.ensureSeeded(false);
7099
+ const cleanTarget = String(targetIdOrAll || "all").trim();
7100
+ const exportMode = mode === "full" ? "full" : "structure";
7101
+ let targetSurveys = [];
7102
+ if (!cleanTarget || cleanTarget === "all") {
7103
+ targetSurveys = await strapi.db.query(SURVEY_UID).findMany({
7104
+ orderBy: { id: "asc" }
7105
+ }) || [];
7106
+ } else {
7107
+ const single = await this.findRawByIdOrSlug(cleanTarget);
7108
+ if (!single) {
7109
+ return null;
7110
+ }
7111
+ targetSurveys = [single];
7112
+ }
7113
+ const portableSurveys = [];
7114
+ let totalResponses = 0;
7115
+ for (const srv of targetSurveys) {
7116
+ const rawResps = exportMode === "full" ? await this.getResponsesForSurvey(srv) : [];
7117
+ const item = sanitizeSurveyForBundle(srv, rawResps);
7118
+ totalResponses += item.responses.length;
7119
+ portableSurveys.push(item);
7120
+ }
7121
+ const dateStamp = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
7122
+ const modeSuffix = exportMode === "full" ? "full-backup" : "structure";
7123
+ const filename = cleanTarget && cleanTarget !== "all" && portableSurveys[0]?.slug ? `${portableSurveys[0].slug}-${modeSuffix}.ci-survey.json` : `ci-surveys-all-${modeSuffix}-${dateStamp}.ci-survey.json`;
7124
+ const bundle = {
7125
+ packageType: "strapi-content-input-survey-bundle",
7126
+ schemaVersion: 1,
7127
+ mode: exportMode,
7128
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
7129
+ surveyCount: portableSurveys.length,
7130
+ totalResponses,
7131
+ surveys: portableSurveys
7132
+ };
7133
+ return {
7134
+ filename,
7135
+ contentType: "application/json; charset=utf-8",
7136
+ bundle
7137
+ };
7138
+ },
7139
+ async importBundle(rawPayload, options2 = {}) {
7140
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
7141
+ let parsed = rawPayload;
7142
+ if (typeof parsed === "string") {
7143
+ try {
7144
+ parsed = JSON.parse(parsed);
7145
+ } catch {
7146
+ const err = new Error("Invalid JSON bundle payload");
7147
+ err.status = 400;
7148
+ throw err;
7149
+ }
7150
+ }
7151
+ let rawItems = [];
7152
+ if (Array.isArray(parsed)) {
7153
+ rawItems = parsed;
7154
+ } else if (parsed && typeof parsed === "object") {
7155
+ if (Array.isArray(parsed.surveys)) {
7156
+ rawItems = parsed.surveys;
7157
+ } else if (Array.isArray(parsed.questions) || parsed.title || parsed.slug) {
7158
+ rawItems = [parsed];
7159
+ }
7160
+ }
7161
+ const validItems = rawItems.filter(
7162
+ (it) => it && typeof it === "object" && (Array.isArray(it.questions) || it.title)
7163
+ );
7164
+ if (validItems.length === 0) {
7165
+ const err = new Error(
7166
+ "No valid survey definitions found in the provided JSON package."
7167
+ );
7168
+ err.status = 400;
7169
+ throw err;
7170
+ }
7171
+ const conflictStrategy = options2.conflictStrategy === "overwrite" ? "overwrite" : "duplicate";
7172
+ const includeResponses = options2.includeResponses !== false;
7173
+ const existingSurveys = await strapi.db.query(SURVEY_UID).findMany() || [];
7174
+ const usedSlugs = new Set(
7175
+ existingSurveys.map((s) => String(s?.slug || "").trim()).filter(Boolean)
7176
+ );
7177
+ const importedSurveys = [];
7178
+ let importedResponsesCount = 0;
7179
+ for (const item of validItems) {
7180
+ const cleanTitle = String(item.title || "Imported Survey").trim();
7181
+ const baseSlug = slugifyIdentifier(String(item.slug || cleanTitle)) || "imported_survey";
7182
+ const existing = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: baseSlug } });
7183
+ const isOverwriting = Boolean(existing && conflictStrategy === "overwrite");
7184
+ const isDuplicatingCollision = Boolean(
7185
+ existing && conflictStrategy === "duplicate"
7186
+ );
7187
+ const finalSlug = isOverwriting ? baseSlug : makeUniqueSlug(baseSlug, usedSlugs);
7188
+ const finalTitle = isDuplicatingCollision ? `${cleanTitle} (Copy)` : cleanTitle;
7189
+ const rawTitleI18n = item.titleI18n && typeof item.titleI18n === "object" ? { ...item.titleI18n } : { tr: cleanTitle, en: cleanTitle };
7190
+ if (isDuplicatingCollision) {
7191
+ for (const k of Object.keys(rawTitleI18n)) {
7192
+ if (rawTitleI18n[k]) {
7193
+ rawTitleI18n[k] = `${rawTitleI18n[k]} (${k === "tr" ? "Kopya" : "Copy"})`;
7194
+ }
7195
+ }
7196
+ }
7197
+ const savePayload = {
7198
+ ...isOverwriting ? { id: existing.documentId || existing.id } : {},
7199
+ title: finalTitle,
7200
+ titleI18n: rawTitleI18n,
7201
+ slug: finalSlug,
7202
+ description: item.description ?? { tr: "", en: "" },
7203
+ status: item.status || "published",
7204
+ displayMode: item.displayMode || "single_page",
7205
+ startsAt: item.startsAt || null,
7206
+ endsAt: item.endsAt || null,
7207
+ quotaLimit: item.quotaLimit ? Number(item.quotaLimit) : null,
7208
+ submissionPolicy: item.submissionPolicy || "one_per_voter",
7209
+ anonymizeIp: item.anonymizeIp !== void 0 ? Boolean(item.anonymizeIp) : true,
7210
+ showPublicResults: item.showPublicResults || "after_vote",
7211
+ allowBackNavigation: item.allowBackNavigation !== void 0 ? Boolean(item.allowBackNavigation) : true,
7212
+ showProgressBar: item.showProgressBar !== void 0 ? Boolean(item.showProgressBar) : true,
7213
+ useRecaptcha: item.useRecaptcha !== void 0 ? Boolean(item.useRecaptcha) : false,
7214
+ recaptchaSiteKey: item.recaptchaSiteKey ? String(item.recaptchaSiteKey) : "",
7215
+ steps: Array.isArray(item.steps) ? item.steps : [],
7216
+ questions: Array.isArray(item.questions) ? item.questions : [],
7217
+ settings: item.settings && typeof item.settings === "object" ? item.settings : {}
7218
+ };
7219
+ await this.save(savePayload);
7220
+ const savedRaw = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: finalSlug } });
7221
+ if (!savedRaw) continue;
7222
+ const rawResponses = Array.isArray(item.responses) ? item.responses : [];
7223
+ if (includeResponses) {
7224
+ if (isOverwriting) {
7225
+ await this.deleteResponsesForSurveyRecord(savedRaw);
7226
+ }
7227
+ if (rawResponses.length > 0) {
7228
+ const surveyDocOrId = String(savedRaw.documentId || savedRaw.id);
7229
+ const batchSize = 50;
7230
+ for (let i = 0; i < rawResponses.length; i += batchSize) {
7231
+ const chunk = rawResponses.slice(i, i + batchSize);
7232
+ await Promise.all(
7233
+ chunk.map((r) => {
7234
+ const answers = r?.answers && typeof r.answers === "object" && !Array.isArray(r.answers) ? r.answers : {};
7235
+ const otherTexts = r?.otherTexts && typeof r.otherTexts === "object" && !Array.isArray(r.otherTexts) ? r.otherTexts : {};
7236
+ const metrics = computeResponseMetrics(
7237
+ savedRaw,
7238
+ answers
7239
+ );
7240
+ 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;
7241
+ return strapi.db.query(SURVEY_RESPONSE_UID).create({
7242
+ data: {
7243
+ surveyId: surveyDocOrId,
7244
+ surveySlug: savedRaw.slug,
7245
+ surveyTitle: savedRaw.title,
7246
+ surveyVersion: Number(savedRaw.version || 1),
7247
+ answers,
7248
+ otherTexts,
7249
+ score: typeof r?.score === "number" ? r.score : metrics.score,
7250
+ npsValue: typeof r?.npsValue === "number" ? r.npsValue : metrics.npsValue,
7251
+ npsCategory: r?.npsCategory || metrics.npsCategory,
7252
+ locale: String(r?.locale || "en"),
7253
+ durationSeconds,
7254
+ voterHash: r?.voterHash || null,
7255
+ respondentToken: r?.respondentToken || null,
7256
+ ip: null,
7257
+ userAgent: String(r?.userAgent || "imported"),
7258
+ submittedAt: r?.submittedAt || r?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
7259
+ }
7260
+ });
7261
+ })
7262
+ );
7263
+ }
7264
+ importedResponsesCount += rawResponses.length;
7265
+ }
7266
+ }
7267
+ const finalAdminObj = await this.findOneAdmin(finalSlug);
7268
+ if (finalAdminObj) {
7269
+ importedSurveys.push(finalAdminObj);
7270
+ }
7271
+ }
7272
+ return {
7273
+ ok: true,
7274
+ importedCount: importedSurveys.length,
7275
+ importedResponsesCount,
7276
+ importedSurveys
7277
+ };
6687
7278
  }
6688
7279
  });
6689
7280
  const PALETTE_UID = "plugin::content-input.ci-color-palette";